Wednesday, 28 November 2012 02:16

Lock Excel Cell or Cells in C#, VB.NET

Written by  support iceblue
Rate this item
(0 votes)

Excel cells lock is a mainly used to protect a certain cell or part of cells in Excel worksheet. As long as the Excel cell or cells are locked, any edition on the locked cells are forbidden such as insert and modify data, change data property in the locked cells etc. This section will introduce a solution to lock Excel cell or cells via a .NET Excel component in C#, VB.NET.

Spire.XLS for .NET, with rich features in editing, reading and manipulating Excel files, enables you to quickly lock Excel cell or cells in C#, VB.NET. In the solution, you only need to set the Worksheet class property: Worksheet.Range.Style.Locked to be true. For example, you can lock A1 in the first worksheet by workbook.Worksheets[0].Range["A1"].Style.Locked = true; Now ,please see the target Excel file as below picture:

Lock Excel Cells

Here you can Download Spire.XLS for .NET and add Spire.XLS dll in your system. Then, perform lock Excel cells task by below code.

Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
            Spire.Xls.Worksheet sheet = workbook.Worksheets[0];

            sheet.Range["A1"].Text = "Locked";
            sheet.Range["B1"].Text = "Unlocked";

            sheet.Range["A1"].Style.Locked = true;
            sheet.Range["B1"].Style.Locked = false;

            sheet.Protect("123", SheetProtectionType.All);

            workbook.SaveToFile(@"Sample_Lock.xlsx", ExcelVersion.Version2013);
Dim workbook As New Spire.Xls.Workbook()
Dim sheet As Spire.Xls.Worksheet = workbook.Worksheets(0)

sheet.Range("A1").Text = "Locked"
sheet.Range("B1").Text = "Unlocked"

sheet.Range("A1").Style.Locked = true
sheet.Range("B1").Style.Locked = false

sheet.Protect("123", SheetProtectionType.All)

workbook.SaveToFile("Sample_Lock.xlsx", ExcelVersion.Version2013)

Additional Info

  • tutorial_title: Lock Excel Cell
Last modified on Wednesday, 10 December 2014 02:48