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.

[C#]
using Spire.Xls;
namespace lock_excel_cells
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"D:\michelle\my file\lock worksheet.xls");
            //lock a certain excel cell A1 in the first worksheet
            workbook.Worksheets[0].Range["A1"].Style.Locked = true;
            //lock excel cells A2:B10 in the first worksheet
            workbook.Worksheets[0].Range["A2:B10"].Style.Locked = true;
            //Lock a certain excel cell A1 in the second worksheet
            workbook.Worksheets[1].Range["A1"].Style.Locked = true;
            //lock excel cells A2:B10 in the first worksheet
            workbook.Worksheets[1].Range["A2:B10"].Style.Locked = true;
            //save excel file
            workbook.SaveToFile("result.xls");
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace lock_excel_cells
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            Dim workbook As Workbook = New Workbook
            workbook.LoadFromFile("D:\michelle\my file\lock worksheet.xls")
            'lock a certain excel cell A1 in the first worksheet
            workbook.Worksheets(0).Range("A1").Style.Locked = true
            'lock excel cells A2:B10 in the first worksheet
            workbook.Worksheets(0).Range("A2:B10").Style.Locked = true
            'Lock a certain excel cell A1 in the second worksheet
            workbook.Worksheets(1).Range("A1").Style.Locked = true
            'lock excel cells A2:B10 in the first worksheet
            workbook.Worksheets(1).Range("A2:B10").Style.Locked = true
            'save excel file
            workbook.SaveToFile("result.xls")
        End Sub
    End Class
End Namespace

Additional Info

  • tutorial_title: Lock Excel Cell
Last modified on Thursday, 10 July 2014 08:52