Apache POI(3):给Excel文件添加打开密码

来源:互联网 发布:微博来自mac客户端 编辑:程序博客网 时间:2024/05/01 13:22
package com.hthk.iisz.util;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;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;/* * 给xlsx的excel文件设置打开文件的密码 */public class ExcelPasswordUtils { /*  * excelFilePath : excel文件路径  * excelPassword : 打开文件密码  */ public static void  encryptExcel(String excelFilePath,String excelPassword) throws Exception{File fileSoucre = new File(excelFilePath);// Add password protection and encrypt the filePOIFSFileSystem fs = new POIFSFileSystem();EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);Encryptor enc = info.getEncryptor();// set the passwordenc.confirmPassword(excelPassword);// encrypt the fileOPCPackage opc = OPCPackage.open(fileSoucre,PackageAccess.READ_WRITE);OutputStream os = enc.getDataStream(fs);opc.save(os);opc.close();// save the file back to the filesystemFileOutputStream fos = new FileOutputStream(fileSoucre);fs.writeFilesystem(fos);fos.close();    }}

0 0