读取密码保护的Excel文件(.xlsx)格式使用Java [英] Read Password protected excel file(.xlsx) using Java

查看:6780
本文介绍了读取密码保护的Excel文件(.xlsx)格式使用Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试下面的code,

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);

它抛出一个错误编译错误:无法实例类型解密

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

But eventually this method will need me to copy and create new workbook in which i can read the data.


  1. 为什么我不能够实例解密?

  2. 是否有任何其他的方式比这一点,这样我可以简单的读取受保护的密码excel文件,而无需创建一个副本

  1. Why i'm not able to instantiate Decryptor?
  2. 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打开一个文件是不是推荐当按照文档,因为它的速度较慢,更高的内存(一切都得到缓冲)。相反,你的code确实应该:

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

这篇关于读取密码保护的Excel文件(.xlsx)格式使用Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆