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.
-
- Workbookworkbook = newWorkbook();
- workbook.LoadFromFile("sample.xlsx");
-
- workbook.Protect("test");
- workbook.SaveToFile("ProtectedExcel.xlsx", ExcelVersion.Version2010);
The protected Workbook is given for the reference.
Part 2
Protect only the first worksheet in Excel Workbook.
-
- Workbookworkbook = newWorkbook();
- workbook.LoadFromFile("sample.xlsx");
-
- workbook.Worksheets[0].Protect("abc", SheetProtectionType.All);
- workbook.SaveToFile("ProtectedWorksheet.xlsx", ExcelVersion.Version2010);
The protected Worksheet is given for the reference.
Part 3
Lock certain cells in Excel Worksheet.
-
- Workbookworkbook = newWorkbook();
- workbook.LoadFromFile("sample.xlsx");
- Worksheet sheet = workbook.Worksheets[0];
-
- workbook.Worksheets[0].Range["A1A15"].Style.Locked = true;
-
- workbook.Worksheets[0].Range["B1"].Style.Locked = false;
- sheet.Protect("123", SheetProtectionType.All);
- workbook.SaveToFile("ProtectedExcelCells.xlsx", ExcelVersion.Version2010);
The protected Excel cells are given for the reference.
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.