1. 概要
只需要使用POI,就可以实现Excel文件的加密、解密,简洁方便。
2. pom
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
3. 代码
public class EncryptAndDecryptExcel {
public static void main(String[] args) {
encryptExcel("D:\\study\\test.xlsx", "D:\\study\\test1.xlsx", "111");
decriptExcel("D:\\study\\test1.xlsx", "D:\\study\\test2.xlsx", "111");
}
/**
* 加密excel文件
*
* @param oldFileName 待加密文件,带路径
* @param newFileName 加密后文件,带路径,可覆盖原文件
* @param password 密码
*/
public static void encryptExcel(String oldFileName, String newFileName, String password) {
InputStream in = null;
OPCPackage opc = null;
FileOutputStream fos = null;
POIFSFileSystem fs = null;
try {
in = new FileInputStream(oldFileName);
//创建POIFS文件系统,加密文件
fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(password);
//将输入流输入到OPCPackage里
opc = OPCPackage.open(in);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
opc.flush();
// 保存加密文件
fos = new FileOutputStream(newFileName);
fs.writeFilesystem(fos);
fos.flush();
System.out.println("加密并保存成功");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (opc != null) {
opc.close();
}
if (fos != null) {
fos.close();
}
if (in != null) {
in.close();
}
if (fs != null) {
fs.close();
}
} catch (Exception ex1) {
ex1.printStackTrace();
}
}
}
/**
* 解密excel文件
*
* @param oldFileName 待解密文件,带路径
* @param newFileName 解密后文件,带路径,可覆盖原文件
* @param password 密码
*/
public static void decriptExcel(String oldFileName, String newFileName, String password) {
try {
Workbook workbook = WorkbookFactory.create(new File(oldFileName), password);
// 测试,输入文件里的内容
System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0));
// 直接保存就是去除密码后的文件了
workbook.write(new FileOutputStream(newFileName));
System.out.println("解密并保存成功");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}