Read Password protected excel file(.xlsx)

2019-08-15 17:32发布

问题:

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