This short tutorial guides on how to password protect an Excel file in C# with the help of all the necessary steps to configure the IDE and detailed steps to write the application. It also provides a runnable sample code that exhibits the process to encrypt Excel file with password in C#. You will also learn about different encryption types, setting passwords, and saving the output file in different formats like XLSX, XLS, ODS, etc.
Steps to Password Protect Excel in C#
- Establish the environment to use Aspose.Cells for .NET to encrypt an Excel file
- Load or create an Excel file using the Workbook class object
- Set the required encryption options for the loaded workbook using the SetEncryptionOptions() method
- Set the password for the file
- Save the encrypted Workbook on the disk
These steps describe the process to password protect Excel file in C# such that first the source Excel file is loaded and then SetEncryptionOptions() method is used to set different encryption properties for the spreadsheet. After these steps, we just need to set the password that will be required to open the Excel file and then save the output Excel file in your desired format.
Code to Encrypt Workbook with Password in C#
This code demonstrates the process to encrypt Excel file in C# by using the SetEncryptionOptions() method that takes one of the encryption type values like StrongCryptographicProvider, EnhancedCryptographicProviderV1, Compatible, or XOR and the key length. The Settings object in the Workbook class has the password property that is set and required to open the Workbook after encryption. Once the workbook is encrypted, it can be saved in any of the MS Excel-supported formats.
In this article, we have learned to encrypt the Excel file. If you want to learn the process to add a digital signature to a Workbook, refer to the article on how to add digital signature in Excel using C#.