How to protect certain cells in a worksheet?

8 Dec 20233 minutes to read

All the cells in an Excel worksheet have a Locked property, which determines if the cell will be editable. When a worksheet is protected, all the cells in the worksheet get locked, by default.

However, there is often a need to protect only certain cells in a worksheet. In this scenario, you need to protect a worksheet, and set the Locked property as false for the cells that need to be made editable.

The following code snippet illustrate this.

using (ExcelEngine excelEngine = new ExcelEngine())
{
  IApplication application = excelEngine.Excel;
  FileStream inputStream = new FileStream("Sample.xlsx", FileMode.Open, FileAccess.Read);
  IWorkbook workbook = application.Workbooks.Open(inputStream, ExcelOpenType.Automatic);
  IWorksheet worksheet = workbook.Worksheets[0];

  //Sample data
  worksheet.Range["A1:K20"].Text = "Locked";

  //A1:A10 will not be protected, hence it is editable.
  worksheet.Range["A1:A10"].CellStyle.Locked = false;
  worksheet.Range["A1:A10"].Text = "UnLocked";
  worksheet.Protect("syncfusion", ExcelSheetProtection.All);

  FileStream stream = new FileStream("ProtectCells.xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
  workbook.SaveAs(stream);
  workbook.Close();
  excelEngine.Dispose();
}
using (ExcelEngine excelEngine = new ExcelEngine())
{
  IApplication application = excelEngine.Excel;
  application.DefaultVersion = ExcelVersion.Excel2013;
  IWorkbook workbook = application.Workbooks.Open("Sample.xlsx", ExcelOpenType.Automatic);
  IWorksheet worksheet = workbook.Worksheets[0];

  //Sample data
  worksheet.Range["A1:K20"].Text = "Locked";

  //A1:A10 will not be protected, hence it is editable.
  worksheet.Range["A1:A10"].CellStyle.Locked = false;
  worksheet.Range["A1:A10"].Text = "UnLocked";
  worksheet.Protect("syncfusion", ExcelSheetProtection.All);
  workbook.SaveAs("ProtectCells.xlsx");
}
Using excelEngine As ExcelEngine = New ExcelEngine()
  Dim application As IApplication = excelEngine.Excel
  application.DefaultVersion = ExcelVersion.Excel2013
  Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx", ExcelOpenType.Automatic)
  Dim worksheet As IWorksheet = workbook.Worksheets(0)

  'Sample data
  worksheet.Range("A1:K20").Text = "Locked"

  'A1:A10 will not be protected.
  worksheet.Range("A1:A10").CellStyle.Locked = False
  worksheet.Range("A1:A10").Text = "UnLocked"
  worksheet.Protect("syncfusion", ExcelSheetProtection.All)
  workbook.SaveAs("ProtectCells.xlsx")
End Using

NOTE

Locking/Unlocking cells in an unprotected worksheet has no effect.

See Also