OfficeUtils.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package cn.keking.utils;
  2. import org.apache.commons.lang3.exception.ExceptionUtils;
  3. import org.apache.poi.extractor.ExtractorFactory;
  4. import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
  5. import org.springframework.lang.Nullable;
  6. import java.io.IOException;
  7. import java.nio.file.Files;
  8. import java.nio.file.Paths;
  9. /**
  10. * Office工具类
  11. *
  12. * @author ylyue
  13. * @since 2022/7/5
  14. */
  15. public class OfficeUtils {
  16. private static final String POI_INVALID_PASSWORD_MSG = "Invalid password specified";
  17. /**
  18. * 判断office(word,excel,ppt)文件是否受密码保护
  19. *
  20. * @param path office文件路径
  21. * @return 是否受密码保护
  22. */
  23. public static boolean isPwdProtected(String path) {
  24. try {
  25. ExtractorFactory.createExtractor(Files.newInputStream(Paths.get(path)));
  26. } catch (IOException e) {
  27. if (POI_INVALID_PASSWORD_MSG.equals(e.getMessage())) {
  28. return true;
  29. }
  30. } catch (Exception e) {
  31. Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
  32. for (Throwable throwable : throwableArray) {
  33. if (throwable instanceof IOException && POI_INVALID_PASSWORD_MSG.equals(throwable.getMessage())) {
  34. return true;
  35. }
  36. }
  37. }
  38. return false;
  39. }
  40. /**
  41. * 判断office文件是否可打开(兼容)
  42. *
  43. * @param path office文件路径
  44. * @param password 文件密码
  45. * @return 是否可打开(兼容)
  46. */
  47. public static synchronized boolean isCompatible(String path, @Nullable String password) {
  48. try {
  49. Biff8EncryptionKey.setCurrentUserPassword(password);
  50. ExtractorFactory.createExtractor(Files.newInputStream(Paths.get(path)));
  51. } catch (Exception e) {
  52. return false;
  53. } finally {
  54. Biff8EncryptionKey.setCurrentUserPassword(null);
  55. }
  56. return true;
  57. }
  58. }