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.

  1. //create an Excel instance and load the document from file
  2. Workbookworkbook = newWorkbook();
  3. workbook.LoadFromFile("sample.xlsx");
  4. //protect the whole workbook
  5. workbook.Protect("test");
  6. workbook.SaveToFile("ProtectedExcel.xlsx", ExcelVersion.Version2010);
The protected Workbook is given for the reference.

protected

Part 2

Protect only the first worksheet in Excel Workbook.
  1. //create an Excel instance and load the document from file
  2. Workbookworkbook = newWorkbook();
  3. workbook.LoadFromFile("sample.xlsx");
  4. //protect specified worksheet
  5. workbook.Worksheets[0].Protect("abc", SheetProtectionType.All);
  6. workbook.SaveToFile("ProtectedWorksheet.xlsx", ExcelVersion.Version2010);
The protected Worksheet is given for the reference.

protected

Part 3

Lock certain cells in Excel Worksheet.
  1. //create an Excel instance and load the document from file
  2. Workbookworkbook = newWorkbook();
  3. workbook.LoadFromFile("sample.xlsx");
  4. Worksheet sheet = workbook.Worksheets[0];
  5. //lock certain cells
  6. workbook.Worksheets[0].Range["A1A15"].Style.Locked = true;
  7. //unlock certain cells
  8. workbook.Worksheets[0].Range["B1"].Style.Locked = false;
  9. sheet.Protect("123", SheetProtectionType.All);
  10. workbook.SaveToFile("ProtectedExcelCells.xlsx", ExcelVersion.Version2010);
The protected Excel cells are given for the reference.

protected

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.