Read Password protected excel file(.xlsx) using Java

ぐ巨炮叔叔 提交于 2019-12-11 09:46:43

问题


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

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.

  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?

Note : I have looked at this post reading excel file, but doesn't help my exact situation


回答1:


Ah, I've spotted your problem. It's this line:

Decryptor d = new Decryptor(info);

As shown in the Apache POI Encryption documentation, that line needs to be

Decryptor d = Decryptor.getInstance(info);

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)

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
}

Finally, get the decrypted data, and pass that to XSSFWorkbook to read the encrypted workbook



来源:https://stackoverflow.com/questions/25994772/read-password-protected-excel-file-xlsx-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!