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

如何检查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); . . .