Excel加密07版本及03版本
所需jar
poi-3.10-FINAL.jar
poi-ooxml-3.10-FINAL.jar
poi-ooxml-schemas-3.10-FINAL.jar
poi-scratchpad-3.8-beta5-20111217.jar
package com.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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;
import com.jxcell.CellException;
public class ExcelEncryptorUtil {
private static Logger logger = Logger.getLogger(ExcelEncryptorUtil.class);
/**
* 描述 加密07版Excel
*
* @param password
* @param file
* @throws IOException
* @throws InvalidFormatException
* @throws GeneralSecurityException
* @author liNan
* @created 2018年10月31日 下午2:33:34
*/
public static void encryptXlsx(String password, File file) {
OPCPackage opc = null;
FileOutputStream fos = null;
try {
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(password);
opc = OPCPackage.open(file, PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
fos = new FileOutputStream(file);
fs.writeFilesystem(fos);
} catch (InvalidFormatException e) {
logger.error(e.toString());
e.printStackTrace();
} catch (FileNotFoundException e) {
logger.error(e.toString());
e.printStackTrace();
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
} catch (GeneralSecurityException e) {
logger.error(e.toString());
e.printStackTrace();
} finally {
try {
if (opc != null) {
opc.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
}
}
}
/**
* 描述 加密03版本Excel
*
* @param file
* @param password
* @throws IOException
* @throws CellException
* @author liNan
* @created 2018年10月31日 下午2:40:28
*/
public static void encryptXls(File file, String password) {
FileInputStream in = null;
FileOutputStream fos = null;
try {
in = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(in);
workbook.writeProtectWorkbook(password, "admin");
fos = new FileOutputStream(file);
workbook.write(fos);
} catch (Exception e) {
logger.error(e.toString());
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
}
}
}
}