Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Excerpt

There may be times when you want to lock your Excel worksheet so that end users cannot edit or manipulate the data in a worksheet. You can implement worksheet protection using ExcelWriter by calling the

...

method Worksheet.Protect().

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.

...

Code Block
c#
c#
titleWorkbook Encryption

//--- To encrypt a workbook, use the Workbook.EncryptPassword property:
ExcelApplication xlw = new ExcelApplication();
Workbook wb = xlw.Create();
wb.EncryptPassword = "myPassword";
xlw.Save(wb, outPath);

How to Activate Worksheet Protection with ExcelWriter

...

Create a workbook in Microsoft Excel, open click the Tools menuReview tab, and select Protection -> 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.

Image RemovedImage Added

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.

Code Block
c#
c#

ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Create();
Worksheet ws = wb.Worksheet[0];
ws.Protect("MyPassword");

...

  1. Select a cell or cells to unlock.
  2. From the Format menu select CellsRight click and hit Format Cell(s)...
  3. Select the Protection tab.
  4. Uncheck Locked.

Image RemovedImage Added

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:

Code Block
c#
c#

ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Create();
Worksheet ws = wb.Worksheet[0];

//--- Turn on worksheet protection.
ws.Protect("MyPassword");

//--- Create an "unlocked" style.
Style unlockedStyle = wb.CreateStyle();
unlockedStyle.CellLocked = false;

//--- Apply the style.
ws.Cells["A1"].Style = unlockedStyle;
ws.Cells["B1"].Style = unlockedStyle;