使用 Java 读取受密码保护的 excel 文件 (.xlsx) [英] Read Password protected excel file(.xlsx) using Java
问题描述
我已经尝试了下面的代码,
I have tried the below code,
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("D://protectedfile.xlsx"));
EncryptionInfo info = new EncryptionInfo(fs);
Decryptor d = new Decryptor(info); //Error
d.verifyPassword(Decryptor.DEFAULT_PASSWORD);
它抛出一个错误编译错误:无法实例化Decryptor类型
It throws an error compilation error : Cannot instantiate the type Decryptor
但最终这种方法需要我复制并创建新的工作簿,我可以在其中读取数据.
But eventually this method will need me to copy and create new workbook in which i can read the data.
- 为什么我无法实例化 Decryptor?
- 除此之外还有其他方法吗,以便我可以简单地读取受密码保护的 excel 文件而无需创建副本?
- Why i'm not able to instantiate Decryptor?
- Is there any other way than this, so that i can simply read the password protected excel file without creating a copy of it?
注意:我看过这篇文章阅读excel文件,但没有帮助我的具体情况
Note : I have looked at this post reading excel file, but doesn't help my exact situation
推荐答案
啊,我发现了你的问题.这是这一行:
Ah, I've spotted your problem. It's this line:
Decryptor d = new Decryptor(info);
如Apache POI 加密文档所示,该行需要
Decryptor d = Decryptor.getInstance(info);
建议您查看有关加密的 POI 文档,并确保您使用的是最新版本的 Apache POI(撰写本文时为 3.11 beta 2)
You'd be well advised to review the POI docs on encryption, and also make sure you're using the latest version of Apache POI (3.11 beta 2 as of writing)
此外,不推荐从 InputStream 打开文件,根据文档,因为它更慢,内存更高(一切都必须缓冲).相反,您的代码应该是:
Additionally, opening a File from an InputStream isn't recommended, as per the documentation, as it's slower and higher memory (everything has to get buffered). Instead, your code should really be:
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("D://protectedfile.xlsx"));
EncryptionInfo info = new EncryptionInfo(fs);
Decryptor d = Decryptor.getInstance(info);
if (d.verifyPassword("password")) {
XSSFWorkbook wb = new XSSFWorkbook(d.getDataStream(fs));
} else {
// Password is wrong
}
最后,获取解密后的数据,并将其传递给 XSSFWorkbook 以读取加密的工作簿
Finally, get the decrypted data, and pass that to XSSFWorkbook to read the encrypted workbook
这篇关于使用 Java 读取受密码保护的 excel 文件 (.xlsx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!