gpt4 book ai didi

java - 如何使用 apache poi 检查 xlsx 文件是否受密码保护

转载 作者:行者123 更新时间:2023-12-01 20:17:03 26 4
gpt4 key购买 nike

如何检查 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);
.
.
.

关于java - 如何使用 apache poi 检查 xlsx 文件是否受密码保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58951813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com