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 file
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
// set the password
enc.confirmPassword(excelPassword);
// encrypt the file
OPCPackage opc = OPCPackage.open(fileSoucre,PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
opc.close();
// save the file back to the filesystem
FileOutputStream fos = new FileOutputStream(fileSoucre);
fs.writeFilesystem(fos);
fos.close();
}
}