How to Lock or Unlock Excel Cells in WPF

When sharing an excel worksheet, we may want to protect some valuable or important data from being changed by others. With Spire.XLS, we can easily achieve this by locking excel cells. Once locked, we will not be able to modify data from the protected cells until we unlock them. This article will explain how to lock or unlock excel cells in WPF using Spire.XLS for WPF.

Generally, there are two main steps when locking cells in an excel worksheet:

  • Locking specific cells.
  • Applying sheet protection – locking cells has no effect until we protect the worksheet.

Detail steps and code snippets are as following:

Step 1: Initialize a new instance of Workbook class, load the sample excel file and get its first worksheet.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Worksheet sheet = workbook.Worksheets[0];

Step 2: Lock or unlock specified cells.

By default, all cells in an Excel worksheet are locked, so we need to unlock them first, next lock the specified cells and protect the worksheet with password.

sheet.Range.Style.Locked = false;
sheet.Range["A1:B3"].Style.Locked = true;
sheet.Protect("123", SheetProtectionType.All);

If you want to unlock excel cells, please use the following line of code:

sheet.Range["A1:B3"].Style.Locked = false;

Step 3: Save the changes and launch the file.

workbook.SaveToFile("locked.xlsx");
System.Diagnostics.Process.Start("locked.xlsx");

Effective screenshot after locking excel cells:

How to Lock or Unlock Excel Cells in WPF

Full codes:

using Spire.Xls;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];

            //Lock excel cells
            sheet.Range.Style.Locked = false;
            sheet.Range["A1:B3"].Style.Locked = true;
            sheet.Protect("123", SheetProtectionType.All);

            //Unlock excel cells
            // sheet.Range["A1:B3"].Style.Locked = false;

            workbook.SaveToFile("locked.xlsx");
            System.Diagnostics.Process.Start("locked.xlsx");
        }

    }
}