Worksheet protection is meant to lock data for the purpose of presentation only. Worksheet protection should not be confused with encryption, and it should not be used to hide or protect sensitive data. When worksheet protection is activated, users can see the worksheet and all the data within it, but will be prevented from altering the content or formatting the cells.
Encryption can be performed on the workbook level, as shown below:
How to Activate Worksheet Protection with ExcelWriter
Using ExcelWriter, there are two ways to write-protect worksheets in your workbook:
Protect in Microsoft Excel and Open in ExcelWriter
Create a workbook in Microsoft Excel, click the Review tab, and select Protect sheet. Next, select the password you want to protect with and the properties you would like to set and click OK. Then, open the spreadsheet with ExcelWriter script, using either ExcelTemplate or ExcelApplication.Open. ExcelWriter will preserve all existing spreadsheet settings, including worksheet protection.
Protect in ExcelWriter Code
Use the method Worksheet.Protect to active worksheet protection. Pass the method a password for unlocking the worksheet in Excel. Pass "" or nullto protect the worksheet without a password.
Removing Worksheet Protection
To remove worksheet protection in Microsoft Excel,
- From the Tools menu, select Protection -> Unprotect Sheet.
- If a password was set, enter it and click Ok.
To remove worksheet protection with ExcelWriter, call Worksheet.Unprotect:
Protecting Specific Cells
When you activate worksheet protection, all of the cells in the worksheet will be locked by default. However, you can unlock cells within a protected worksheet, allowing the user to fill in or modify some fields.
To unlock cells in Microsoft Excel:
- Select a cell or cells to unlock.
- Right click and hit Format Cell(s)...
- Select the Protection tab.
- Uncheck Locked.
With ExcelWriter, you can unlock cells by setting Style.CellLocked to false and applying the style to an individual cell. The following example protects all cells except for A1 and B1: