python excel表格 xlsx 和 xls 转换

package excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.jxcell.CellException;
import com.jxcell.View;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class crypt {

    /**
     * 读取excel,并进行加密
     *
     * @param url excel文件路径 例:D:\\word.xls
     * @param pwd 加密密码
     */
    public static void encrypt(String url, String pwd) {
        View m_view = new View();
        try {
            // read excel
            m_view.read(url);
            // set the workbook open password
            m_view.write(url, pwd);
            System.out.print("ok");
        } catch (CellException e) {
            System.out.println(url);
            System.out.println(pwd);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用POI给Excel文件加密
     * @param filePath
     * @param pwd
     * @throws Exception
     */
    public static void encryptExcel(String filePath,String pwd) throws Exception{

        POIFSFileSystem fs = new POIFSFileSystem();
        EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
        //final EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes256, HashAlgorithm.sha256, -1, -1, null);
        Encryptor enc = info.getEncryptor();

        //设置密码
        enc.confirmPassword(pwd);

        //加密文件
        OPCPackage opc = OPCPackage.open(new File(filePath), PackageAccess.READ_WRITE);
        OutputStream os = enc.getDataStream(fs);
        opc.save(os);
        opc.close();

        //把加密后的文件写回到流
        FileOutputStream fos = new FileOutputStream(filePath);
        fs.writeFilesystem(fos);
        fos.close();
    }

    /**
     * excel 解密
     *
     * @return void
     * @author lifq
     * @date 2015-3-13 下午02:15:49
     */
    public static void decrypt(String url, String pwd) {
        View m_view = new View();
        try {
            // read the encrypted excel file
            m_view.read(url, pwd);

            // write without password protected
            m_view.write(url);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static void main(String args[]) {

        // args[0] 文件路径
        // args[1] 文件密码
//        System.out.println(args[0]);
//        System.out.println(args[1]);
        try {
            crypt.encryptExcel(args[0], args[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 

你可能感兴趣的:(Java)