如何检查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。
最佳答案
第一,
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);
.
.
.