如何使用 POI api 在 Java 中访问受密码保护的 Excel 工作簿

问题描述:

我想读取和写入受密码保护的 Excel 文件.我怎样才能使用 Apache POI API 做到这一点.

I want to read from and write to password protected Excel files. How can I do so using Apache POI API.

POI 应该能够打开受保护的 xls 文件(使用 org.apache.poi.hssf.record.crypt)和受保护的xlsx 文件(使用 org.apache.poi.poifs.crypt).你试过这些吗?

POI should be able to open both protected xls files (using org.apache.poi.hssf.record.crypt) and protected xlsx files (using org.apache.poi.poifs.crypt). Have you tried these?

如果您使用 HSSF(用于 xls 文件),则需要在打开文件之前设置密码.您可以通过以下方式调用:

If you're using HSSF (for a xls file), you need to set the password before opening the file. You do this with a call to:

 org.apache.poi.hssf.record.crypto.Biff8EncryptionKey.setCurrentUserPassword(password);

之后,HSSF 应该能够打开您的文件.

After that, HSSF should be able to open your file.

对于 XSSF,您需要以下内容:

For XSSF, you want something like:

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("protect.xlsx"));
EncryptionInfo info = new EncryptionInfo(fs);
Decryptor d = new Decryptor(info);
d.verifyPassword(Decryptor.DEFAULT_PASSWORD);
XSSFWorkbook wb = new XSSFWorkbook(d.getDataStream(fs));

.

或者,在较新版本的 Apache POI 中,WorkbookFactory 支持在打开时提供密码,因此您可以执行以下操作:

Alternately, in newer versions of Apache POI, WorkbookFactory supports supplying the password when opening, so you can just do something like:

Workbook wb = WorkbookFactory.create(new File("protected.xls"), "password");

这对 HSSF 和 XSSF 都适用,根据格式选择正确的,并以适当的格式传递给定的密码.

That will work for both HSSF and XSSF, picking the right one based on the format, and passing in the given password in the appropriate way for the format.