Skip to content

Sheet Protection

Aleksei edited this page May 28, 2021 · 4 revisions
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Protected No-Password");

ws.Protect()                                               // On this sheet we will only allow:
  .AllowElement(XLSheetProtectionElements.FormatCells)   // Cell Formatting
  .AllowElement(XLSheetProtectionElements.InsertColumns) // Inserting Columns
  .AllowElement(XLSheetProtectionElements.DeleteColumns) // Deleting Columns
  .AllowElement(XLSheetProtectionElements.DeleteRows);   // Deleting Rows

ws.Cell("A1").SetFormulaA1("\"Locked, No Hidden (Default):\"").Style.Font.SetBold().Fill.SetBackgroundColor(XLColor.Cyan);
ws.Cell("B1").Style
  .Border.SetOutsideBorder(XLBorderStyleValues.Medium);

ws.Cell("A2").SetFormulaA1("\"Locked, Hidden:\"").Style.Font.SetBold().Fill.SetBackgroundColor(XLColor.Cyan);
ws.Cell("B2").Style
  .Protection.SetHidden()
  .Border.SetOutsideBorder(XLBorderStyleValues.Medium);

ws.Cell("A3").SetFormulaA1("\"Not Locked, Hidden:\"").Style.Font.SetBold().Fill.SetBackgroundColor(XLColor.Cyan);
ws.Cell("B3").Style
  .Protection.SetLocked(false)
  .Protection.SetHidden()
  .Border.SetOutsideBorder(XLBorderStyleValues.Medium);

ws.Cell("A4").SetFormulaA1("\"Not Locked, Not Hidden:\"").Style.Font.SetBold().Fill.SetBackgroundColor(XLColor.Cyan);
ws.Cell("B4").Style
  .Protection.SetLocked(false)
  .Border.SetOutsideBorder(XLBorderStyleValues.Medium);

ws.Columns().AdjustToContents();

// Protect a sheet with a password
var protectedSheet = wb.Worksheets.Add("Protected Password = 123");
var protection = protectedSheet.Protect("123");
protection.AllowedElements = XLSheetProtectionElements.InsertRows |
                             XLSheetProtectionElements.InsertColumns;

wb.SaveAs("SheetProtection.xlsx");

FAQ

Examples

Real world scenarios

Time Savers

Performance and Memory

Misc

Inserting Data/Tables

Styles

Ranges

Rows

Columns

Page Setup (Print Options)

AutoFilters

Comments

Dev docs

Clone this wiki locally