Java protects Excel workbooks and worksheets

Posted by Kodak07 on Thu, 16 Apr 2020 16:26:40 +0200

For security reasons, you may need to protect the entire workbook or worksheet. Sometimes, you may even need to protect a worksheet, but keep the specified cells for editing. This article describes how to use free fire.xls for Java to implement these operations.

 

Add Spire.Xls.jar as a dependency

Method 1: Download Free Spire.XLS for Java Package and extract it, then add the spirit.xls.jar package as a dependency to your Java application from the lib folder.

 

Method 2: if you want to use maven, you can easily install the JAR package into your Maven project by adding the following configuration to the pom.xml file.

 

<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>2.2.0</version>
  </dependency>
</dependencies>

 

Protect Workbook

import com.spire.xls.*;

public class EncryptWorkbook {
    public static void main(String[] args) {
        //Load sample document
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

        //Use password encryption protection
        workbook.protect("abc123");

        //Save document
        workbook.saveToFile("Protect Workbook.xlsx", ExcelVersion.Version2010);

    }
}

 

Protection worksheet

import com.spire.xls.*;
import java.util.EnumSet;
public class ProtectWorksheet { public static void main(String[] args) { //Load sample document Workbook workbook = new Workbook(); workbook.loadFromFile("Sample.xlsx"); //Get first sheet Worksheet sheet = workbook.getWorksheets().get(0); //Use password encryption protection sheet.protect("abc123", EnumSet.of(SheetProtectionType.All)); //Save document workbook.saveToFile("Protection worksheet.xlsx", ExcelVersion.Version2010); } }

 

 

Protect sheet but unlock some cell ranges

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

public class UnlockCell {
    public static void main(String[] args) {
        //Load sample document
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

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

        //Password encryption protection worksheet
        sheet.protect("abc123", EnumSet.of(SheetProtectionType.All));

        //Unlock some cells
        sheet.getCellRange("A2:B11").getCellStyle().setLocked(false);

        //Save document
        workbook.saveToFile("Unlock cell.xlsx", ExcelVersion.Version2016);
    }
}

Topics: Java Maven xml nexus