Introduction
When a worksheet is protected, user's actions are restricted. For example, you cannot input data. Moreover, you can't insert or delete rows or columns etc. There are only 3 protection options in MS Excel 97 and Excel 2000:
- Contents
- Objects
- Scenarios
Protected worksheet doesn't hide or protect sensitive data, so it's different from file encryption. Generally, worksheet protection is suitable for presentation purposes. It prevents the end users from modifying the data, content and formatting in the worksheet.
Protect a Worksheet
Aspose.Cells provides a class, Workbook that represents an Excel file. Workbook class contains a Worksheets collection that allows to access each worksheet in the Excel file. A worksheet is represented by the Worksheet class.
Worksheet class provides Protect method that is used to apply appropriate protection on the worksheet. Protect method accepts the following parameters:
- Protection Type, represents the type of protection to apply on the worksheet. Protection type is applied with the help of ProtectionType enumeration
- New Password, represents the new password that is used to protect the worksheet
- Old Password, represents the old password, if the worksheet is already protected by a password. If the worksheet is not already protected then just pass a null
ProtectionType enumeration contains the following pre-defined protections types:
|
Protection Types
|
Description
|
|
All
|
User cannot modify anything on this worksheet
|
|
Contents
|
User cannot enter data in this worksheet
|
|
Objects
|
User cannot modify drawing objects
|
|
Scenarios
|
User cannot modify saved scenarios
|
Example:
An example is given below that is used to protect a worksheet with a password.
[C#]
//Instantiating a Workbook object
Workbook excel=new Workbook();
//Creating a file stream containing the Excel file to be opened
FileStream fstream=new FileStream("C:\\book1.xls",FileMode.Open);
//Opening the Excel file through the file stream
excel.Open(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet=excel.Worksheets[0];
//Protecting the worksheet with a password
worksheet.Protect(ProtectionType.All,"salman",null);
//Saving the modified Excel file in default (that is Excel 20003) format
excel.Save("C:\\output.xls",FileFormatType.Default);
//Closing the file stream to free all resources
fstream.Close();
[VB.NET]
'Instantiating a Workbook object
Dim excel As Workbook = New Workbook
'Creating a file stream containing the Excel file to be opened
Dim fstream As FileStream = New FileStream("C:\\book1.xls",FileMode.Open)
'Opening the Excel file through the file stream
excel.Open(fstream)
'Accessing the first worksheet in the Excel file
Dim worksheet As Worksheet = excel.Worksheets(0)
'Protecting the worksheet with a password
worksheet.Protect(ProtectionType.All,"salman",null)
'Saving the modified Excel file in default (that is Excel 20003) format
excel.Save("C:\\output.xls",FileFormatType.Default)
'Closing the file stream to free all resources
fstream.Close()
[JAVA]
//Instantiating a Workbook object
Workbook excel=new Workbook();
//Opening the Excel file
excel.open("F:\\book1.xls");
Worksheets worksheets = excel.getWorksheets();
Worksheet worksheet = worksheets.getSheet(0);
Protection protection = new Protection();
//The following 3 methods are only for Excel 2000 and earlier formats
protection.setEditingContentsAllowed(false);
protection.setEditingObjectsAllowed(false);
protection.setEditingScenariosAllowed(false);
//Protects the first worksheet with a password "1234"
protection.setPassword("1234");
worksheet.protect(protection);
//The following line equals to workbook.write("protected1234.xls", FileFormatType.Excel2003);
excel.save("C:\\protected1234.xls");
After the above code is used to protect the worksheet, you can check the protection on the worksheet by opening it. Once you open the file and try to add some data to the worksheet, you will see the following dialog:
|
Figure: A Message Dialog to notify that user can't modify the worksheet
|
To work on the worksheet, you would need to unprotect the worksheet by selecting the Tools | Protection | Unprotect Sheet menu item as shown below:
|
Figure: Selecting Unprotect Sheet menu item
|
After you select Unprotect Sheet menu item, a dialog will open that would prompt you to enter the password so that you may work on the worksheet as shown below:
|
Figure: Entering password to unprotect the worksheet
|
Protect a few Cells in the Worksheet
There might be certain scenarios where you need to lock a few cells only in the worksheet. If you want to lock some specific cells in the worksheet, you have to unlock all the other cells in the worksheet. All the cells in a worksheet are already initialized for locking, you may check this opening any excel file into MS Excel and click the Format | Cells...to show Format Cells dialog box and then click the Protection tab and see a check box labeled "Locked" is checked by default.
Following are the two approaches to implement the task.
Method1
The following points describe how to lock a few cells using MS Excel. This method applies to Microsoft Office Excel 2003, Microsoft Excel 97, 2000, and 2002.
1. Select the entire worksheet by clicking the Select All button (the gray rectangle directly above the row number for row 1 and to the left of column letter A).
2. Click Cells on the Format menu, click the Protection tab, and then clear the Locked check box.
This unlocks all the cells on the worksheet
Note If the Cells command is not available, parts of the worksheet may already be locked. On the Tools menu, point to Protection, and then click Unprotect Sheet.
3. Select just the cells you want to lock and repeat step 2, but this time select the Locked check box.
On the Tools menu, point to Protection, click Protect Sheet, and then click OK.
Note In the Protect Sheet dialog box, you have the option to specify a password and select the elements that you want users to be able to change.
Method2
In this method, we use Aspose.Cells API only to do the task.
Example:
The following example exhibits how to protect a few cells in the worksheet. It unlocks all the cells in the worksheet first and then locks 3 cells (A1, B1, C1) in it. Finally, it protects the worksheet. A row / column has a Style property that further contains a boolean property, IsLocked . You can set IsLocked property to true or false to lock or unlock the row / column.
[C#]
// Create a new workbook.
Workbook wb = new Workbook();
// Create a worksheet object and obtain the first sheet.
Worksheet sheet = wb.Worksheets[0];
// Define the style object.
Style style;
// Loop through all the columns in the worksheet and unlock them.
for(int i = 0; i <= 255; i ++)
{
style = sheet.Cells.Columns[(byte)i].Style;
style.IsLocked = false;
}
// Lock the three cells...i.e. A1, B1, C1.
style = sheet.Cells["A1"].Style;
style.IsLocked = true;
style = sheet.Cells["B1"].Style;
style.IsLocked = true;
style = sheet.Cells["C1"].Style;
style.IsLocked = true;
// Finally, Protect the sheet now.
Aspose.Cells.Protection protection = sheet.Protection;
// Save the excel file.
wb.Save("d:\\test\\lockedcells.xls", FileFormatType.ExcelXP);
[VB.NET]
' Create a new workbook.
Dim wb As Workbook = New Workbook()
' Create a worksheet object and obtain the first sheet.
Dim sheet As Worksheet = wb.Worksheets(0)
' Define the style object.
Dim style As Style
Dim i As Integer
' Loop through all the columns in the worksheet and unlock them.
For i = 0 To 255
style = sheet.Cells.Columns(Convert.ToByte(i)).Style
style.IsLocked = False
Next
' Lock the three cells...i.e. A1, B1, C1.
style = sheet.Cells("A1").Style
style.IsLocked = True
style = sheet.Cells("B1").Style
style.IsLocked = True
style = sheet.Cells("C1").Style
style.IsLocked = True
' Finally, Protect the sheet now.
Dim protection As Aspose.Cells.Protection = sheet.Protection
' Save the excel file.
wb.Save("d:\test\lockedcells.xls", FileFormatType.ExcelXP)
[JAVA]
// Create a new workbook.
Workbook wb = new Workbook();
// Create a worksheet object and obtain the first sheet.
Worksheet sheet = wb.getWorksheets().getSheet(0);
// Define the style object.
Style style;
// Loop through all the columns in the worksheet and unlock them.
for(int i = 0; i <= 255; i ++)
{
style = sheet.getCells().getColumns().getColumn(i).getStyle();
style.setCellLocked(false);
}
// Lock the three cells...i.e. A1, B1, C1.
style = sheet.getCells().getCell("A1").getStyle();
style.setCellLocked(true);
style = sheet.getCells().getCell("B1").getStyle();
style.setCellLocked(true);
style = sheet.getCell("C1").getStyle();
style.setCellLocked(true);
// Finally, Protect the sheet now.
Protection protection = new Protection();
sheet.protect(protection);
// Save the excel file.