To include the necessary components for document manipulation, you can add the library to your project build path either manually or via a dependency manager.
Mavan Configuration
Add the repository and dependency entries below to your pom.xml file to retrieve the artifact automatically:
<repositories>
<repository>
<id>e-iceblue</id>
<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>
Alternatively, download the package from the vendor site, extract Spire.Xls.jar, and link it directly within your IDE’s libraries list.
Securing the Workbook Srtucture
Encrypting at the workbook level restricts unauthoirzed viewing and modification of the entire file.
import com.spire.xls.*;
public class SecureDocument {
public static void main(String[] args) {
// Instantiate and load the source file
Workbook doc = new Workbook();
doc.loadFromFile("sample_input.xlsx");
// Apply password protection
doc.protect("StrongP@ssword!");
// Export the secured document
doc.saveToFile("secured_workbook.xlsx", ExcelVersion.Version2010);
}
}
Restricting Worksheet Access
Individual sheets can be locked independently, with specific permission settings applied to them.
import com.spire.xls.*;
import java.util.EnumSet;
public class LockSheets {
public static void main(String[] args) {
Workbook excelDoc = new Workbook();
excelDoc.loadFromFile("template.xlsx");
// Retrieve the target sheet
Sheet target = excelDoc.getWorksheets().get(0);
// Enable protection on the worksheet
target.protect("EditMe!", EnumSet.of(SheetProtectionType.All));
excelDoc.saveToFile("restricted_sheet.xlsx", ExcelVersion.Version2010);
}
}
Configuring Editable Areas
You may lock a sheet globally while permitting modifications on specific designated ranges.
import com.spire.xls.*;
import java.util.EnumSet;
public class ManageAccess {
public static void main(String[] args) {
Workbook app = new Workbook();
app.loadFromFile("base_data.xlsx");
Sheet ws = app.getWorksheets().get(0);
// Configure specific range as unlocked first
CellRange range = ws.getCellRange("C5:D15");
range.getCellStyle().setLocked(false);
// Apply protection to the rest of the sheet
ws.protect("InputAllowed", EnumSet.of(SheetProtectionType.All));
app.saveToFile("editable_range.xlsx", ExcelVersion.Version2016);
}
}