簡體   English   中英

如何使用apache poi檢查xlsx文件是否受密碼保護

[英]How to check if xlsx file is password protected or not using 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。

如果你不知道你擁有什么,但你知道密碼,那么你應該使用WorkbookFactory.create並將密碼傳遞給它,例如

Workbook wb = WorkbookFactory.create(new File("protected.xls"),
                                     "NiceSecurePassword");

WorkbookFactory將識別該類型,然后為您調用適當的解密和工作簿加載。 如果文件未受保護,則將忽略密碼

如果您確定該文件是基於.xlsx的,但不確定它是否受到保護,那么您可以執行以下操作:

Workbook wb = null;
try {
   wb = new XSSFWorkbook(new File("test.xlsx"));
} catch (EncryptedDocumentException e) {
   // Password protected, try to decrypt and load
}

如果你給XSSFWorkbook一個受密碼保護的.xlsx文件,它會拋出一個EncryptedDocumentException你可以捕獲然后根據你已經獲得的代碼嘗試解密

嘗試使用

XSSFWorkbook wb = new XSSFWorkbook(dataStream);

來自Apache POI:“HSSF是POI項目的Excel '97(-2007)文件格式的純Java實現.XSSF是POI項目的Excel 2007 OOXML(.xlsx)文件格式的純Java實現。” http://poi.apache.org/spreadsheet/您正在XLSX文件上使用HSSF(適用於xls)。

第一,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM