EXCEL Workbook Protection in C#, VB.NET

  • Demo
  • C# source
  • VB.Net source

The sample demonstrates how to lock and unlock an excel workbook.

using System;

using Spire.Xls;

namespace CellProtection
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();

            //Initialize worksheet
            workbook.CreateEmptySheets(1);
            Worksheet sheet = workbook.Worksheets[0];

            //Set the password
            Console.Write("Please input password:");
            string str = Console.ReadLine();
            Console.ReadKey();

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

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

            //Protect workbook
            workbook.Protect(str);
            workbook.SaveToFile("Sample.xls");
            System.Diagnostics.Process.Start(workbook.FileName);
        }
    }
}

Imports Spire.Xls
Module Module1

    Sub Main()
    
        Dim workbook As Workbook = New Workbook()

        'Initialize worksheet
        workbook.CreateEmptySheets(1)
        Dim sheet As Worksheet = workbook.Worksheets(0)

        'Protect workshet
        Console.Write("Please input password:")
        Dim str As String = Console.ReadLine()
        Console.ReadKey()

        sheet.Protect(str)

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

        sheet.Range("A1").Style.Locked = True
        sheet.Range("B1").Style.Locked = False

        'Protect workbook
        workbook.Protect(str)

        workbook.SaveToFile("Sample.xls")
        System.Diagnostics.Process.Start(workbook.FileName)
    End Sub
End Module