How to Protect Excel with C# – Encrypt with Password and Lock Cell

Nowadays, information is sent quickly with network which leads that some important information cannot be protected and let out. Therefore, MS Excel Provides users with function to protect Excel file to confirm that data will not be stolen when sending.

In this post, I want to introduce a method about how to protect Excel by using C#, including to encrypt whole Excel workbook and lock cell in worksheet.

Encrypt Excel

Excel encryption means that user sets a password for one Excel cell file and others (contain owner) should have the correct password to view data information in Workbook. Generally speaking, if data information is secret or very important, users may adopt this method to protect Excel.

Lock Cell

Cell lock means that lock one or a range of cells to prevent other from editing. Also, users can set a password when locking cell. If others want to edit cell, they should enter the correct password. Cell lock allows users to view data without password but cannot edit.

Following, I will show detailed steps about how to protect Excel.

Note: In this method, I used a component, Spire.XLS. And I have added its dll file as reference in my project before coding.

  1. Load Excel file which I want to protect from computer and then initialize worksheet.
  2. Use sheet.Protect(“Password”) to lock cells. Please note that this method is used to lock all the cells in this worksheet.
  3. Set one unlocked cell by assign false value to sheet.Range[].Style.Locked
  4. encrypt Excel by using workbook.Protect(“Password”). 
  5. Save this protected Excel and launch it.

Use the following code:

using System;
using Spire.Xls;

namespace ProtectExcel
    class Encryption
        static void Main(string[] args)
            //Get Excel File
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@”D:\Work\My Documents\Customer.xlsx”);

            //Initailize worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Protect cells

            //Set Unlocked Cell
            sheet.Range[“A1”].Style.Locked = false;

            //Protect Workbook

            //Save and Launch
            workbook.SaveToFile(“Protected.xlsx”, ExcelVersion.Version2010);

After running, we can get the result as following:

Protect Whole Workbook:

Protect Current Worksheet:

Unlocked Cell:


Click Here to LEARN MORE about Spire.XLS

Click Here to DOWNLOAD Spire.XLS


2 thoughts on “How to Protect Excel with C# – Encrypt with Password and Lock Cell

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s