如何使用apache poi检查xlsx文件是否受密码保护 [英] How to check if xlsx file is password protected or not using apache poi
本文介绍了如何使用apache poi检查xlsx文件是否受密码保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查 xlsx 文件是否受密码保护.我们可以按如下方式检查 xls 文件
How to check if xlsx file is password protected or not. we can check for xls file as follows
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.
But the above code works for only xls not for xlsx.
推荐答案
首先
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);
.
.
.
这篇关于如何使用apache poi检查xlsx文件是否受密码保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文