2022-07-21 03:19:46 +00:00
|
|
|
|
package cn.keking.utils;
|
|
|
|
|
|
|
|
|
|
|
|
import org.apache.commons.lang3.exception.ExceptionUtils;
|
|
|
|
|
|
import org.apache.poi.extractor.ExtractorFactory;
|
|
|
|
|
|
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
|
|
|
|
|
|
import org.springframework.lang.Nullable;
|
|
|
|
|
|
|
|
|
|
|
|
import java.io.FileInputStream;
|
2022-11-10 18:27:39 +08:00
|
|
|
|
import java.io.IOException;
|
2022-07-21 03:19:46 +00:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* Office工具类
|
|
|
|
|
|
*
|
|
|
|
|
|
* @author ylyue
|
|
|
|
|
|
* @since 2022/7/5
|
|
|
|
|
|
*/
|
|
|
|
|
|
public class OfficeUtils {
|
|
|
|
|
|
|
2022-11-10 18:27:39 +08:00
|
|
|
|
private static final String POI_INVALID_PASSWORD_MSG = "Invalid password specified";
|
|
|
|
|
|
|
2022-07-21 03:19:46 +00:00
|
|
|
|
/**
|
|
|
|
|
|
* 判断office(word,excel,ppt)文件是否受密码保护
|
|
|
|
|
|
*
|
|
|
|
|
|
* @param path office文件路径
|
|
|
|
|
|
* @return 是否受密码保护
|
|
|
|
|
|
*/
|
|
|
|
|
|
public static boolean isPwdProtected(String path) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
ExtractorFactory.createExtractor(new FileInputStream(path));
|
2022-11-10 18:27:39 +08:00
|
|
|
|
} catch (IOException e) {
|
|
|
|
|
|
if (POI_INVALID_PASSWORD_MSG.equals(e.getMessage())) {
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
2022-07-21 03:19:46 +00:00
|
|
|
|
} catch (Exception e) {
|
2022-11-10 18:27:39 +08:00
|
|
|
|
Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
|
|
|
|
|
|
for (Throwable throwable : throwableArray) {
|
|
|
|
|
|
if (throwable instanceof IOException && POI_INVALID_PASSWORD_MSG.equals(throwable.getMessage())) {
|
2022-07-21 03:19:46 +00:00
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 判断office文件是否可打开(兼容)
|
|
|
|
|
|
*
|
|
|
|
|
|
* @param path office文件路径
|
|
|
|
|
|
* @param password 文件密码
|
|
|
|
|
|
* @return 是否可打开(兼容)
|
|
|
|
|
|
*/
|
|
|
|
|
|
public static synchronized boolean isCompatible(String path, @Nullable String password) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
Biff8EncryptionKey.setCurrentUserPassword(password);
|
|
|
|
|
|
ExtractorFactory.createExtractor(new FileInputStream(path));
|
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
|
return false;
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
Biff8EncryptionKey.setCurrentUserPassword(null);
|
|
|
|
|
|
}
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|