1 excel文件加密
excel文件分为两种:以xlsx结尾的文件以及xls结尾的文件,针对于这两种不同类型的文件加密的方法也不太一样,使用的 poi-4.1.1.jar和commons-math3-3.6.1.jar这两个apache的工具jar。
1.1 xlsx的加密
代码如下:
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
Encryptor enc = info.getEncryptor();
enc.confirmPassword(pwd);
OPCPackage opc = OPCPackage.open(new File(fullFileName), PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
opc.close();
os.close();
fos = new FileOutputStream(fullFileName);
fs.writeFilesystem(fos);
fos.flush();
1.2 xls的加密
代码如下:
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fullFileName));
HSSFWorkbook wb = new HSSFWorkbook(fs);
Biff8EncryptionKey.setCurrentUserPassword(pwd);
wb.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(),"admin");
wb.unwriteProtectWorkbook();
fos = new FileOutputStream(fullFileName);
wb.write(fos);