Data security has become more and more important since the internet spreads the data more quickly than we can imagine. We always use Excel files to store a large amount of the data, which is very important to us in our daily life. Thus, in this blog, we are going to give you a detailed introduction about how to protect Excel files with a password in C#. I searched on NuGet and I am lucky enough to have found free Spire.XLS. It works like a charm, so I’d like to share it with you guys.
This blog introduces
- How to lock the whole Excel Workbook with the password in C#.
- How to lock some special Worksheet with the password in C#.
- How to lock certain cells in the Worksheet in C#.
Please note this library can create or load Excel files independently. Here, Microsoft Excel is only used to view the effect.
Part 1
Protect the whole Excel Workbook with the password.
- //create an Excel instance and load the document from file
- Workbookworkbook = newWorkbook();
- workbook.LoadFromFile("sample.xlsx");
- //protect the whole workbook
- workbook.Protect("test");
- workbook.SaveToFile("ProtectedExcel.xlsx", ExcelVersion.Version2010);

Part 2
Protect only the first worksheet in Excel Workbook.
- //create an Excel instance and load the document from file
- Workbookworkbook = newWorkbook();
- workbook.LoadFromFile("sample.xlsx");
- //protect specified worksheet
- workbook.Worksheets[0].Protect("abc", SheetProtectionType.All);
- workbook.SaveToFile("ProtectedWorksheet.xlsx", ExcelVersion.Version2010);

Part 3
Lock certain cells in Excel Worksheet.
- //create an Excel instance and load the document from file
- Workbookworkbook = newWorkbook();
- workbook.LoadFromFile("sample.xlsx");
- Worksheet sheet = workbook.Worksheets[0];
- //lock certain cells
- workbook.Worksheets[0].Range["A1A15"].Style.Locked = true;
- //unlock certain cells
- workbook.Worksheets[0].Range["B1"].Style.Locked = false;
- sheet.Protect("123", SheetProtectionType.All);
- workbook.SaveToFile("ProtectedExcelCells.xlsx", ExcelVersion.Version2010);

Conclusion
Thanks to Spire.XLS, due to which I am able to show you how to protect/encrypt Excel Workbook, Excel Worksheets and certain Excel cells programmatically in C#. I hope, you have gained a deeper understanding of the security in Excel after reading my blog. Besides encrypting Excel file formats with the password, it also supports unlocking and decoding Excel files. Thanks a lot for your reading. Happy coding and have a good day.
Tapan ParidaPosted Jul 17, 2018, 4:00 AM
Please share complete code. so that i can use it. I have a data with in datagridview. I want to export it and lock certain cells in that Worksheet.