使用Java读取受密码保护的excel文件(.xlsx)

时间:2014-09-23 12:08:50

标签: java selenium selenium-webdriver apache-poi jxl

我尝试过以下代码,

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

但最终这种方法需要我复制并创建新的工作簿,我可以在其中读取数据。

  1. 为什么我无法实例化Decryptor?
  2. 除此之外是否有其他方式,以便我可以读取受密码保护的Excel文件而不创建其副本
  3. 注意:我查看过这篇文章reading excel file,但对我的确切情况没有帮助

1 个答案:

答案 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以读取加密的工作簿

相关问题