我如何使用POI API来访问受密码保护的Excel工作簿中的Java [英] How can I access password protected Excel workbook in Java using POI api

查看:3237
本文介绍了我如何使用POI API来访问受密码保护的Excel工作簿中的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要读取和写入密码保护的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更新版本,<一个href=\"http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/WorkbookFactory.html#create%28java.io.File,%20java.lang.String%29\"相对=nofollow> 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.

这篇关于我如何使用POI API来访问受密码保护的Excel工作簿中的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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