How to Read password protected Excel in java?


Using Apache POI library we can read protected Excel file easily in Java

Apache POI

POI Allows us to read both Excel file formats




Reading protected documents is format-dependent and needs to be implemented per format differently.

Reading password protected XLS file

Use Biff8EncryptionKey.setCurrentUserPassword(password) to specify the decryption password before reading the workbook of the XLS file.

Reading password protected XLSX file

POIFSFileSystem fs = new POIFSFileSystem(xlsxFile); EncryptionInfo info = new EncryptionInfo(fs); Decryptor decryptor = Decryptor.getInstance(info); //Verifying the password if (!decryptor.verifyPassword("javacodepoint")) {        throw new RuntimeException("Incorrect password"); }           InputStream dataStream = decryptor.getDataStream(fs); // Now parse dataStream

Generic logic for Reading both XLS and XLSX file

In Apache POI, WorkbookFactory is a factory class available for creating the appropriate kind of Workbook (eg. HSSFWorkbook or XSSFWorkbook), by auto-detecting from the supplied input.

For example- WorkbookFactory.create( file, java.lang.String password);