C#/VB.NET: Lock Specific Cells in Excel

When creating an Excel worksheet, you may enter some data or formulas that you don't wish other users to modify. Locking the corresponding cells can be essential to maintain the integrity of the data and formulas. In this article, you will learn how to lock specific cells in Excel in C# and VB.NET using Spire.XLS for .NET library.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Lock Specific Cells in Excel in C# and VB.NET

Normally, the locked option is enabled for all cells in a worksheet. Therefore, before locking a cell or range of cells, all cells must be unlocked. Keep in mind that locking cells doesn’t take effect until the worksheet is protected.

The following are the main steps to lock cells in Excel:

  • Create an instance of Workbook class.
  • Load the Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet using Workbook.Worksheet[sheetIndex] property.
  • Access the used range in the worksheet and then unlock all the cells in the range by setting the CellRange.Style.Locked property as false.
  • Access specific cells and then lock them by setting the CellRange.Style.Locked property as true.
  • Protect the worksheet using XlsWorksheetBase.Protect() method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace LockCells
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Unlock all cells in the used range of the worksheet
            CellRange usedRange = sheet.Range;            
            usedRange.Style.Locked = false;

            //Lock specific cells
            CellRange cells = sheet.Range["A1:C3"]; 
            cells.Style.Locked = true;

            //Protect the worksheet with password
            sheet.Protect("123456", SheetProtectionType.All);

            //Save the result file
            workbook.SaveToFile("LockCells.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Lock Specific Cells in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.