Files
ClosedXML/ClosedXML_Examples/Misc/SheetProtection.cs
T
Thom Lamb 2cd6df6481 Initial commit of the ClosedXML library
Establishes the foundational structure, core Excel functionality, and tooling.

- Implements base components for cells, ranges, columns, and rows.
- Integrates a custom calculation engine with a wide range of Excel functions.
- Adds comprehensive support for styling, conditional formatting, data validation, comments, pictures, and charts.
- Configures build setup, project metadata (NuGet), and developer guidelines.
- Includes editor and Git attributes for consistent code style and line endings.
2026-06-23 11:02:53 -05:00

59 lines
2.2 KiB
C#

using ClosedXML.Excel;
using System;
using static ClosedXML.Excel.XLProtectionAlgorithm;
namespace ClosedXML_Examples.Misc
{
public class SheetProtection : IXLExample
{
public void Create(String filePath)
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Protected No-Password");
ws.Protect().AllowElement
(
// On this sheet we will only allow:
XLSheetProtectionElements.FormatCells
| XLSheetProtectionElements.InsertColumns
| XLSheetProtectionElements.DeleteColumns
| XLSheetProtectionElements.DeleteRows
| XLSheetProtectionElements.EditScenarios
);
ws.Cell("A1").SetValue("Locked, No Hidden (Default):").Style.Font.SetBold().Fill.SetBackgroundColor(XLColor.Cyan);
ws.Cell("B1").Style
.Border.SetOutsideBorder(XLBorderStyleValues.Medium);
ws.Cell("A2").SetValue("Locked, Hidden:").Style.Font.SetBold().Fill.SetBackgroundColor(XLColor.Cyan);
ws.Cell("B2").Style
.Protection.SetHidden()
.Border.SetOutsideBorder(XLBorderStyleValues.Medium);
ws.Cell("A3").SetValue("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").SetValue("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", Algorithm.SimpleHash);
protection.AllowElement
(
XLSheetProtectionElements.InsertRows
| XLSheetProtectionElements.InsertColumns
);
wb.SaveAs(filePath);
}
}
}