Sunday, 19 January 2020 07:16

How to protect Excel files in Java applications

Written by  support iceblue
Rate this item
(0 votes)

This article demonstrates how to use Spire.XLS for Java to encrypt the Excel files from the following three parts:

  • 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

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("Sample.xlsx");

        //Protect the workbook with the password you want
        workbook.protect("eiceblue");

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

    }
}

Effective screenshot after protected workbook:

How to protect Excel files in Java applications

Only protect the first worksheet on 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("Sample.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);

    }
}

The screenshot of the protected worksheet:

How to protect Excel files in Java applications

Lock some certain cells on 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("Sample.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);

    }
}

Here is the protected Excel cells:

How to protect Excel files in Java applications

Additional Info

  • tutorial_title: Protect Excel files in Java applications
Last modified on Sunday, 19 January 2020 07:33
More in this category: Java unprotect the Excel file »