Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we read protected password excel file (.xls) with POI API

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.

like image 681
embarus Avatar asked Jul 30 '09 03:07

embarus


3 Answers

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

like image 172
Randomness Avatar answered Oct 21 '22 10:10

Randomness


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

like image 24
Gagravarr Avatar answered Oct 21 '22 12:10

Gagravarr


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();
    }

}
like image 26
codester Avatar answered Oct 21 '22 10:10

codester