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.
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.
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.
- Load Excel file which I want to protect from computer and then initialize worksheet.
- Use sheet.Protect(“Password”) to lock cells. Please note that this method is used to lock all the cells in this worksheet.
- Set one unlocked cell by assign false value to sheet.Range.Style.Locked
- encrypt Excel by using workbook.Protect(“Password”).
- Save this protected Excel and launch it.
Use the following code:
static void Main(string args)
//Get Excel File
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets;
//Set Unlocked Cell
sheet.Range[“A1”].Style.Locked = false;
//Save and Launch
After running, we can get the result as following:
Protect Whole Workbook:
Protect Current Worksheet:
Click Here to LEARN MORE about Spire.XLS
Click Here to DOWNLOAD Spire.XLS