Create a password protected Excel file using Apache POI?

Updated: As of version 3.10 POI supports encryption as well as decryption for XLSX files. See the “Encryption Support” page on POI’s website. The below is still relevant for XLS binary workbooks.

According to the “Encryption Support” page on POI’s website POI supports reading encrypted XLS and XLSX files. Encrypting is not mentioned on that page, which implies that it’s not supported. This is backed up by searching the POI site for “encrypt” which returns only a handful of results all of which are about decryption. I’ve also taken a look at the sources for their crypto implementation, which appears to only handle decryption. This isn’t surprising; POI is designed for data extraction and search indexing, not for creating new spreadsheets.

As others have suggested, it’s often possible to work around missing features in POI by creating a template in Excel and then using POI to populate it with data. Unfortunately that won’t work for encryption because the file format of encrypted spreadsheets is radically different.

If you’re willing to pay for commercial software, the latest version of ExtenXLS has full read and write support for all the encryption formats supported by Excel. Just construct an EncryptedWorkBookHandle instead of the normal WorkBookHandle. That will use the strongest possible cipher supported by an unmodified JRE, RC4 for XLS and 128-bit AES for XLSX. If you want to use 256-bit AES with OOXML and you’ve installed the JCE unlimited policy you can do so with the MSOfficeEncrypter class.

JExcelAPI, a popular open-source Java spreadsheet API, does not appear to support encryption at all. Aspose.Cells, a commercial offering, supports stong encryption. The documentation for Actuate’s e.Spreadsheet seems to have disappeared from the ‘net, so I can’t tell whether it supports encryption or not.

Since none of the freely available Java spreadsheet APIs seems to support writing encrypted spreadsheets, if you’re not willing to use commercial software you’ll need to come up with a workaround. You could, for example, write the spreadsheet into an encrypted ZIP file. java.util.zip doesn’t support encryption, but it looks like Zip4j does.

Full disclosure: I work for Extentech, the company behind ExtenXLS.

Leave a Comment