News Category

Easily Lock Excel Worksheet in C#, VB.NET

2011-08-09 03:46:41 Written by  support iceblue
Rate this item
(0 votes)

The most important reason that people lock worksheet when perform tasks in Excel is to protect the original Excel file from editing or modifying by other people. Through Microsoft Excel, you can set the entire Excel worksheet by setting its property as Read Only or just set partial region area cells as Read Only via protecting worksheet. While how to lock worksheet with C#, VB.NET will be the core topic in this section.

Spire.XLS for .NET, as a fast and reliable excel component, enables you to lock your worksheet by setting Worksheet class property: Worksheet.Range.Style.Locked = true. By this component, you can lock any worksheet that you need. In this solution, worksheet one and worksheet two are locked as you view in below picture:

Lock Excel Worksheet

Now, before the detail code, you have to add Spire.Xls dll by download Spire.XLS for .NET.

[C#]
using Spire.Xls;

namespace lock_excel_worksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"..\lock worksheet.xls");
            workbook.Worksheets[0].Range.Style.Locked = true;
            workbook.Worksheets[1].Range.Style.Locked = true;
            workbook.Worksheets[0].Protect("", SheetProtectionType.All);
            workbook.Worksheets[1].Protect("", SheetProtectionType.All);
            workbook.SaveToFile("result.xls",ExcelVersion.Version97to2003);
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace lock_excel_worksheet
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            Dim workbook As Workbook = New Workbook
            workbook.LoadFromFile("..\lock worksheet.xls")
            workbook.Worksheets(0).Range.Style.Locked = true
            workbook.Worksheets(1).Range.Style.Locked = true
            workbook.Worksheets(0).Protect("", SheetProtectionType.All)
            workbook.Worksheets(1).Protect("", SheetProtectionType.All)
            workbook.SaveToFile("result.xls",ExcelVersion.Version97to2003)
        End Sub
    End Class
End Namespace

Spire.XLS allows user to operate Excel document directly such as save to stream, save as web response, copy, lock/unlock worksheet, set up workbook properties, etc. As a professional .NET/Silverlight Excel component, it owns the ability of inserting content into Excel document, formatting cells and converting Excel documents to popular office file formats. Spire.XLS for .NET supports Excel 97-2003, Excel 2007 and Excel 2010.

Additional Info

  • tutorial_title: Lock Excel Worksheet
Last modified on Wednesday, 07 December 2022 01:10