How to create password-protected Excel in java?

This article shows you how to create a password-protected Microsoft Excel file using Apache POI. Microsoft Excel documents generally come in two different formats Excel 97(-2003) and Excel(2007+). ie XLS and XLSX formats.

How to password protect an excel file?

Encryption is format-dependent and needs to be implemented per format differently.

  1. Password protect XLS file
  2. Password protect XLSX file

Creating password-protected XLS file in Java

Since Apache POI 3.16, we can easily protect MS-Excel (.xls) files with passwords in Java. Use Biff8EncryptionKey.setCurrentUserPassword(String password) to specify the decryption password before saving or writing the workbook of the excel file.

Let’s see the below java code example to protect XLS files. We are setting “javacodepoint” as a password here,

CreateProtectedXLSFile.java

package com.javacodepoint.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CreateProtectedXLSFile {

	public static void main(String[] args) throws IOException {

		try {

			// Creating a xlsfile object with specific file path
			File xlsFile = new File("E:/Excel/protected.xls");

			// Setting the file password = javacodepoint
			// It should be called before saving the workbook
			Biff8EncryptionKey.setCurrentUserPassword("javacodepoint");

			// Creating workbook
			HSSFWorkbook workbook = new HSSFWorkbook();

			// Creating sheet
			HSSFSheet sheet = workbook.createSheet("Employee Records");

			// Creating header of the excel sheet
			HSSFRow header = sheet.createRow(0);

			// Creating cell and setting the cell value
			header.createCell(0).setCellValue("Employee Id");
			header.createCell(1).setCellValue("Employee Name");
			header.createCell(2).setCellValue("Age");
			header.createCell(3).setCellValue("Email ID");
			header.createCell(4).setCellValue("Salary");

			// Creating the 1st row to insert employee record
			HSSFRow row1 = sheet.createRow(1);

			// Inserting 1st employee record
			row1.createCell(0).setCellValue("101");
			row1.createCell(1).setCellValue("John william");
			row1.createCell(2).setCellValue("30");
			row1.createCell(3).setCellValue("william.john@gmail.com");
			row1.createCell(4).setCellValue("15000$");

			// Creating the 2nd row
			HSSFRow row2 = sheet.createRow(2);

			// Inserting 2nd employee record
			row2.createCell(0).setCellValue("102");
			row2.createCell(1).setCellValue("Harsh singh");
			row2.createCell(2).setCellValue("35");
			row2.createCell(3).setCellValue("harsh.singh@gmail.com");
			row2.createCell(4).setCellValue("20000$");

			// Creating file output stream to write the workbook data
			FileOutputStream fos = new FileOutputStream(xlsFile);

			// Writing workbook
			workbook.write(fos);

			// Closing the output stream and workbook
			fos.close();
			workbook.close();

			// Printing the success message on the console
			System.out.println("Protected Excel(.xls) file has been created successfully.");

		} catch (IOException e) {
			System.out.println("Exception while creating protected xls file");
			e.printStackTrace();
		}
	}
}

Note: Setting a null password before saving removes the password protection.

For example- Biff8EncryptionKey.setCurrentUserPassword(null);

Creating password-protected XLSX file in Java

Protecting XLSX files using Apache POI, a little complex than protecting XLS files.

Simple steps to create password-protected XLSX files:

  1. Create EncryptionInfo class object.
  2. Get the Encryptor object using getEncryptor() method of EncryptionInfo class.
  3. Set the password using confirmPassword() method of Encryptor class.
  4. Open the xlsx file using OPCPackage.open() in READ_WRITE mode.
  5. Get the output stream using encryptor and then save it.
  6. Write the encrypted data to the file using writeFilesystem() method.

There are multiple encryption modes(eg. standard, agile, binaryRC4, xor, etc.) supported by the Apache POI. To create EncryptionInfo class object, we need to choose one encryption mode among these.

For example:

EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);

Apart from the EncryptionMode, the EncryptionInfo class provides further parameters to specify the cipher and hashing algorithm to be used.

For example:

EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha384, -1, -1, null);

Please note that, If you want to use high encryption parameters, you need to install the “Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files” for your JRE version.

Let’s see the below complete example to understand it better. We are taking “javacodepoint” as a password here,

CreateProtectedXLSXFile.java

package com.javacodepoint.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateProtectedXLSXFile {

	public static void main(String[] args) {
		try {
			// Creating a xlsxfile object with specific file path
			File xlsxFile = new File("E:/Excel/protected.xlsx");

			// Creating workbook
			XSSFWorkbook workbook = new XSSFWorkbook();

			// Creating sheet
			XSSFSheet sheet = workbook.createSheet("Employee Records");

			// Creating header of the sheet
			XSSFRow header = sheet.createRow(0);

			// Creating cell and setting the cell value
			header.createCell(0).setCellValue("Employee Id");
			header.createCell(1).setCellValue("Employee Name");
			header.createCell(2).setCellValue("Age");
			header.createCell(3).setCellValue("Email ID");
			header.createCell(4).setCellValue("Salary");

			// Creating the 1st row to insert employee record
			XSSFRow row1 = sheet.createRow(1);

			// Inserting 1st employee record
			row1.createCell(0).setCellValue("101");
			row1.createCell(1).setCellValue("John william");
			row1.createCell(2).setCellValue("30");
			row1.createCell(3).setCellValue("william.john@gmail.com");
			row1.createCell(4).setCellValue("15000$");

			// Creating the 2nd row
			XSSFRow row2 = sheet.createRow(2);

			// Inserting 2nd employee record
			row2.createCell(0).setCellValue("102");
			row2.createCell(1).setCellValue("Harsh singh");
			row2.createCell(2).setCellValue("35");
			row2.createCell(3).setCellValue("harsh.singh@gmail.com");
			row2.createCell(4).setCellValue("20000$");

			// Write the workbook data to a file
			try (FileOutputStream fos = new FileOutputStream(xlsxFile)) {
				workbook.write(fos);
				fos.close();
				workbook.close();
			}

			// Protecting the excel file
			try (POIFSFileSystem fs = new POIFSFileSystem()) {

				EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
				Encryptor encryptor = info.getEncryptor();

				// Setting the password 'javacodepoint'
				encryptor.confirmPassword("javacodepoint");

				/* Read in an existing OOXML file and write to encrypted output stream
				 * don't forget to close the output stream otherwise the padding bytes
				 * aren't added
                                 */
				try (OPCPackage opc = OPCPackage.open(xlsxFile, PackageAccess.READ_WRITE);
						OutputStream os = encryptor.getDataStream(fs)) {
					opc.save(os);
				}

				// Write out the encrypted version
				try (FileOutputStream fos = new FileOutputStream(xlsxFile)) {
					fs.writeFilesystem(fos);
				}
			}

			System.out.println("Protected Excel(.xlsx) file has been created successfully.");

		} catch (InvalidFormatException | IOException | GeneralSecurityException e) {
			System.out.println("Exception while writting protected xlsx file");
			e.printStackTrace();
		}

	}

}

Required Maven Dependencies

The below maven dependencies you can add in your pom.xml file of the maven project:

<!-- Used for Excel 2003 or before (xls) -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>
 
<!-- Used for Excel 2007 or later (xlsx)  -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>

If you want to create a stand-alone application, then you need to download specific poi jars and configure them to build paths. You can follow the article Apache POI – Getting started to set up the same in Eclipse IDE.

Conclusion

In this article, you have seen how to create or write password-protected Excel files(.xls and .xlsx) in java using the Apache POI library. Of course, for both Excel formats, there are different approaches to do that.

Related Articles:

[Java code] Convert Excel file to CSV with Apache POI
How to create password-protected Excel in java?
How to Read password-protected Excel in java?
How to write data to an existing Excel file in java?

You may also like:

How to create a Stopwatch in JavaScript?
File upload validations in javascript
Preview an image before uploading using Javascript
Preview an image before uploading using jQuery
File Upload in Java Servlet Example
Multiple file upload in Java with Progress bar – Ajax

Share with friends

Leave a Comment

Your email address will not be published.