如何检查xlsx文件是否受密码保护。我们可以检查xls文件如下
FileInputStream fin = new FileInputStream(new File("C:/Book1.xls"));
POIFSFileSystem poifs = new POIFSFileSystem(fin);
EncryptionInfo info = new EncryptionInfo(poifs);
Decryptor d = Decryptor.getInstance(info);
try {
if (!d.verifyPassword(Decryptor.DEFAULT_PASSWORD)) {
throw new RuntimeException("Unable to process: document is encrypted");
}
InputStream dataStream = d.getDataStream(poifs);
HSSFWorkbook wb = new HSSFWorkbook(dataStream);
// parse dataStream
} catch (GeneralSecurityException ex) {
throw new RuntimeException("Unable to process encrypted document", ex);
}
但上述代码仅适用于xls而不适用于xlsx。
答案 0 :(得分:2)
如果你不知道你拥有什么,但是你知道密码,那么你应该使用WorkbookFactory.create并将密码传递给它,例如
Workbook wb = WorkbookFactory.create(new File("protected.xls"),
"NiceSecurePassword");
WorkbookFactory
将识别该类型,然后为您调用适当的解密和工作簿加载。如果文件未受保护,则密码将被忽略
如果您确定该文件基于.xlsx
,但不确定该文件是否受到保护,那么您可以执行以下操作:
Workbook wb = null;
try {
wb = new XSSFWorkbook(new File("test.xlsx"));
} catch (EncryptedDocumentException e) {
// Password protected, try to decrypt and load
}
如果您为XSSFWorkbook提供受密码保护的.xlsx
文件,它会抛出EncryptedDocumentException您可以捕获的内容,然后根据您已经获得的代码尝试解密
答案 1 :(得分:1)
尝试使用
XSSFWorkbook wb = new XSSFWorkbook(dataStream);
来自Apache POI:" HSSF是POI项目的Excel' 97(-2007)文件格式的纯Java实现。 XSSF是POI项目的Excel 2007 OOXML(.xlsx)文件格式的纯Java实现。" http://poi.apache.org/spreadsheet/您正在XLSX文件中使用HSSF(适用于xls)。
答案 2 :(得分:1)
首先,
public boolean isEncrypted(String path) {
try {
try {
new POIFSFileSystem(new FileInputStream(path));
} catch (IOException ex) {
}
System.out.println("protected");
return true;
} catch (OfficeXmlFileException e) {
System.out.println("not protected");
return false;
}
}
然后,
if (isEncrypted(sourcepath)) {
org.apache.poi.hssf.record.crypto.Biff8EncryptionKey.setCurrentUserPassword("1234");
POIFSFileSystem filesystem = new POIFSFileSystem(new FileInputStream(inpFn));
EncryptionInfo info = new EncryptionInfo(filesystem);
Decryptor d = Decryptor.getInstance(info);
if (!d.verifyPassword("1234")) {
System.out.println("Not good");
} else {
System.out.println("Good!");
}
in = d.getDataStream(filesystem);
} else {
in = new FileInputStream(inpFn);
}
try {
XSSFWorkbook wbIn = new XSSFWorkbook(in);
.
.
.