I've just learned POI and find the HSSF is very simple to read and create excel file (.xls). However, I found some problem when want to read excel protected with password. It took me an hour to find this solution on internet.
Please could you help me to solve this problem. I'm very glad if you could give me a code snippet.
Thank you.
See http://poi.apache.org/encryption.html - if you're using a recent enough copy of Apache POI (eg 3.8) then encrypted .xls files (HSSF) and .xlsx files (XSSF) can be decrypted (proving you have the password!)
At the moment you can't write out encrypted excel files though, only un-encrypted ones
At the time you wrote your question, it wasn't easy to do with Apache POI. Since then, support has come on a long way
These days, if you want to open a password protected Excel file, whether .xls
or .xlsx
, for which you know the password, all you need to do is use WorkbookFactory.create(File,Password), eg
File input = new File("password-protected.xlsx");
String password = "nice and secure";
Workbook wb = WorkbookFactory.create(input, password);
That'll identify the type of the file, decrypt it with the given password, and open it for you. You can then read the contents as normal
Here is a complete example code that reads in a protected excel file, decrypts using a password and writes out unprotected excel file
public static void readProtectedBinFile() {
try {
InputStream inp = new FileInputStream("c:\\tmp\\protectedFile.xls");
org.apache.poi.hssf.record.crypto.Biff8EncryptionKey.setCurrentUserPassword("abracadabra");
Workbook wb;
wb = WorkbookFactory.create(inp);
// Write the output to a file
FileOutputStream fileOut;
fileOut = new FileOutputStream("c:\\tmp\\unprotectedworkbook.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With