excel 文件加密
网上搜了很多,试了很多,发现很多都不好使,一直以为是他们版本过久,最后翻了官方文档 ,除了代码更规范了(通过try-resource关流),其他也大同小异。
研究了好久,最后仔细阅读了一下官网的备注,发现写文件之前必须现将OPCPackage流提前关闭,否则不会添加填充字节。
官方文档的示例代码
try (POIFSFileSystem fs = new POIFSFileSystem()) {
// 创建加密信息
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
// EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha384, -1, -1, null);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("foobaa");
// Read in an existing OOXML file and write to encrypted output stream
// don't forget to close the output stream otherwise the padding bytes aren't added
// 一定要提前将opc输出流关闭!!!
try (OPCPackage opc = OPCPackage.open(new File("..."), PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs)) {
opc.save(os);
}
// 写文件
try (FileOutputStream fos = new FileOutputStream("...")) {
fs.writeFilesystem(fos);
}
}
顺便说一下依赖吧,我用的是目前最新版本的apache-poi.4.1 ,之前试的3.14版本,除了一些方法参数有些变得,其他大都差不多。希望能给各位带来帮助
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
版权声明:本文为qq_39626488原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。