且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-29 23:09:23

首先

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);
.
.
.