How to check if xlsx file is password protected or not using apache poi

前端 未结 3 608
广开言路
广开言路 2020-12-07 03:42

How to check if xlsx file is password protected or not. we can check for xls file as follows

FileInputStream fin = new FileInputStream(new File(\"C:/Book1.xl         


        
3条回答
  •  一生所求
    2020-12-07 03:59

    If you don't know what you have, but you know the password, then you should use WorkbookFactory.create and pass the password to it, eg

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

    WorkbookFactory will identify the type, then call the appropriate decryption and workbook loading for you. If the file isn't protected, the password will be ignored

    .

    If you know for sure that the file is .xlsx based, but aren't sure if it is protected or not, then you can do something like:

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

    If you give the XSSFWorkbook a password protected .xlsx file, it'll throw a EncryptedDocumentException which you can catch and then try decrypting, based on the code you've already got

提交回复
热议问题