In this post, we will see how to protect an Excel worksheet with a password using JExcel in Java with a simple example. Protecting an Excel Spreadsheet is a frequently used task and JExcel API can help to achieve this objective. It will be possible to specify a password in the code for this kind of protection. The Java code for worksheet protection is provided below (comments inline)
import java.io.*;
import java.sql.*;
import java.util.Date;
import jxl.*;
import jxl.write.*;
public class ProtectWorksheet {
public static void main(String args[])
{
try {
WritableWorkbook ProtectWorkbook = Workbook.createWorkbook(new File("output.xls"));
WritableSheet Worksheet_to_Protect=ProtectWorkbook.createSheet("SomeInput", 0);
Label label = new Label(0, 0, "SomeData");/* Add data at Cell 0,0 for example */
Worksheet_to_Protect.addCell(label);
SheetSettings Worksheet_settings=Worksheet_to_Protect.getSettings();
Worksheet_settings.setPassword("password"); /* Password for Worksheet */
java.lang.Boolean set_protected = new java.lang.Boolean(true);
Worksheet_settings.setProtected(set_protected);
ProtectWorkbook.write(); /* Save workbook with password settings */
ProtectWorkbook.close(); /* Close Workbook */
}
catch (Exception i){
System.out.println(i);
}
}
}
The worksheet protection is obtained by using "setPassword" method of SheetSettings object. The rest of the code is self explanatory. Got a comment on the code? Let us know.
Sorry, this code did not work. I created an excel spreadsheet and applied the password code. I could still open the sheet, as usual.
ReplyDeleteIs there a way to protect a cell with password instead of the entire sheet ?
ReplyDeleteI need to have some fields that remain editable and other not, is this possible ?
Thank you,
Yannick
as same as Anonymous's comments. it'll not work well. I can still open it without password which I set in my codes.
ReplyDeleteas same as the Anonymous's comments, it'll not work well. I can still open it without password which I set in my codes.
ReplyDelete