Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access password protected Excel workbook in Java using POI api

I want to read from and write to password protected Excel files. How can I do so using Apache POI API.

like image 490
Umesh Avatar asked Jun 15 '10 05:06

Umesh


2 Answers

POI should be able to open both protected xls files (using org.apache.poi.hssf.record.crypt) and protected xlsx files (using org.apache.poi.poifs.crypt). Have you tried these?

If you're using HSSF (for a xls file), you need to set the password before opening the file. You do this with a call to:

 org.apache.poi.hssf.record.crypto.Biff8EncryptionKey.setCurrentUserPassword(password);

After that, HSSF should be able to open your file.

For XSSF, you want something like:

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("protect.xlsx"));
EncryptionInfo info = new EncryptionInfo(fs);
Decryptor d = new Decryptor(info);
d.verifyPassword(Decryptor.DEFAULT_PASSWORD);
XSSFWorkbook wb = new XSSFWorkbook(d.getDataStream(fs));

.

Alternately, in newer versions of Apache POI, WorkbookFactory supports supplying the password when opening, so you can just do something like:

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

That will work for both HSSF and XSSF, picking the right one based on the format, and passing in the given password in the appropriate way for the format.

like image 153
Gagravarr Avatar answered Sep 20 '22 16:09

Gagravarr


If the entire workbook is password protected (by going through the Excel menu File > Save As... > Tools > General Options... then supplying a password) then the file is encrypted and you cannot read from and write to the workbook through POI.

Excel Save As... General Options

like image 36
Bill the Lizard Avatar answered Sep 22 '22 16:09

Bill the Lizard