Skip to content

Instantly share code, notes, and snippets.

@aspose-com-kb
Created February 18, 2026 18:08
Show Gist options
  • Select an option

  • Save aspose-com-kb/f074d600f8939fe7afdf2899e5ad6cf2 to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-kb/f074d600f8939fe7afdf2899e5ad6cf2 to your computer and use it in GitHub Desktop.
Lock Cells in Excel using C#.
using Aspose.Cells;
namespace CellsProtectionSample
{
internal static class Program
{
private const string LicenseFile = "license.lic";
private const string InputPath = "input.xlsx";
private const string OutputPath = "output_locked.xlsx";
private static void Main()
{
ConfigureLicense();
var book = new Workbook(InputPath);
var page = book.Worksheets[0];
// First, make everything editable
ApplyGlobalLock(page, book, isLocked: false);
// Then lock only the cells we want
ApplyCellLock(page, book, "A2", "B2");
// Enforce the lock settings
page.Protect(ProtectionType.All);
book.Save(OutputPath);
}
private static void ConfigureLicense()
{
var lic = new License();
lic.SetLicense(LicenseFile);
}
private static void ApplyGlobalLock(Worksheet sheet, Workbook book, bool isLocked)
{
var style = book.CreateStyle();
style.IsLocked = isLocked;
var flag = new StyleFlag { Locked = true };
sheet.Cells.ApplyStyle(style, flag);
}
private static void ApplyCellLock(Worksheet sheet, Workbook book, params string[] addresses)
{
var lockedStyle = book.CreateStyle();
lockedStyle.IsLocked = true;
foreach (var addr in addresses)
{
sheet.Cells[addr].SetStyle(lockedStyle);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment