Protect Excel files in Java applications

Andrew Wilson
2 min readApr 16, 2021

In daily work and study, in order to prevent some important Excel data from being modified by others during transmission, we could protect the document with password. This article will introduce the following three methods to encrypt Excel files by using Free Spire.XLS for Java.

● Encrypt the whole excel workbook with password in Java
● Protect a certain worksheet with password in Java
● Lock some certain cells on the worksheet in Java

Installation (2 Method)
1# Download the Free Spire.XLS for Java and unzip it, then add the Spire.Xls.jar file to your project as dependency.

2# You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

Encrypt the whole Excel workbook:

import com.spire.xls.*;

public class EncryptWorkbook {
public static void main(String[] args) {
//Create a workbook and load a file
Workbook workbook = new Workbook();
workbook.loadFromFile("data.xlsx");

//Protect the workbook with the password you want
workbook.protect("123-abc");

//Save the Excel file
workbook.saveToFile("output/EncryptWorkbook.xlsx", ExcelVersion.Version2010);

}
}

Only protect the first worksheet in the excel workbook:

import com.spire.xls.*;
import java.util.EnumSet;

public class ProtectWorksheet {
public static void main(String[] args) {
//Create a workbook and load a file
Workbook workbook = new Workbook();
workbook.loadFromFile("data.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Protect this sheet with a password.
sheet.protect("TestPassword", EnumSet.of(SheetProtectionType.All));

//Save the Excel file
workbook.saveToFile("output/ProtectWorksheet.xlsx", ExcelVersion.Version2010);

}
}

Lock some certain cells in the Excel Worksheet:

import com.spire.xls.*;
import java.util.EnumSet;

public class ProtectCell {
public static void main(String[] args) {
//Create a workbook and load a file
Workbook workbook = new Workbook();
workbook.loadFromFile("data.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Protect cell
sheet.getCellRange("B3").getCellStyle().setLocked(true);
sheet.getCellRange("C3").getCellStyle().setLocked(false);

//Protect sheet
sheet.protect("TestPassword", EnumSet.of(SheetProtectionType.All));

//Save the Excel file
workbook.saveToFile("output/ProtectCell.xlsx", ExcelVersion.Version2010);

}
}

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.