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

标签 java apache-poi

如何检查 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/

相关文章:

java - 如何在没有登录页面的情况下使用简单的 Spring Security AuthenticationProvider?

java - 为什么我在现有源上使用 Spring-boot 和 thymeleaf 时会收到错误 404?

java - Apache POI 中的自定义颜色

java - 如何在Java中将Excel行转换为字符串值?

java - 使用 POI 恢复单元格中的粗体文本

java - eclipse 中的 AspectJ LTW - 切入点不适用于静态方法

java - 如何使用java计算Vector中的不同元素?

c# - 将 c# 数据类型转换为等效的 java 数据类型

java - apache poi , DataFormatter 修剪超出十位小数的值

java - 如何在ubuntu上安装apache-poi