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.Range["A1"].Style.Locked = true; Now ,please see the target Excel file as below picture:
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(); workbook.CreateEmptySheets(1); Spire.Xls.Worksheet sheet = workbook.Worksheets; 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() workbook.CreateEmptySheets(1) 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)