我尝试过以下代码,
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);
抛出错误编译错误:Cannot instantiate the type Decryptor
但最终这种方法需要我复制并创建新的工作簿,我可以在其中读取数据。
注意:我查看过这篇文章reading excel file,但对我的确切情况没有帮助
答案 0 :(得分:1)
Decryptor d = new Decryptor(info);
如Apache POI Encryption documentation所示,该行必须
Decryptor d = Decryptor.getInstance(info);
建议您review the POI docs on encryption,并确保使用最新版本的Apache POI(撰写时为3.11 beta 2)
此外,从InputStream打开文件不是recommended, as per the documentation,因为它的速度较慢且内存较高(所有内容都必须进行缓冲)。相反,您的代码应该是:
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以读取加密的工作簿