MS Excel provides an encryption mechanism to protect the data in the spreadsheets from unauthorized users. Along with applying encryption, you can specify the password that is required to open the Excel files. This article covers how to perform the encryption of Excel files from within .NET applications. Particularly, you will learn how to encrypt and decrypt the Excel files using C#.
- C# API to Encrypt or Decrypt Excel Files
- Encrypt Excel Files using C#
- Decrypt Excel Files using C#
- Verify Password of Encrypted Excel File
- Get Free License
C# API to Encrypt or Decrypt Excel Files
In order to perform encryption and decryption operations on Excel files, this article uses Aspose.Cells for .NET API. The API provides simple ways of encrypting and password protecting Excel files with the desired encryption type. You can either download the API or install it within your .NET applications using NuGet.
Install-Package Aspose.Cells
Encrypt Excel Files using C#
Aspose.Cells for .NET supports SHA and AES encryption types in order to encrypt Excel files in the same way as MS Excel does. For Excel 2003 files, you can choose between the following encryption types:
- XOR
- Compatible (Office 97/2000 compatible)
- Enhanced Cryptographic Provider V1
- Strong Cryptographic Provider
The following are the steps to encrypt an Excel file using C#.
- Load the Excel file using Workbook class.
- Use Workbook.SetEncryptionOptions(EncryptionType, int) method to apply the desired encryption.
- Set password using Workbook.Settings.Password property.
- Save the workbook using Workbook.Save(string) method.
The following code sample shows how to encrypt Excel file using C#.
Decrypt Excel Files using C#
The following are the steps to decrypt Excel files using Aspsoe.Cells for .NET API.
- Load the Excel file by providing the path and password to the constructor of Workbook class.
- Set password to null using Workbook.Settings.Password property.
- Save the workbook using Workbook.Save(string) method.
The following code sample shows how to decrypt an Excel file using C#.
Verify Password of Encrypted Excel File using C#
Aspose.Cells for .NET also allows you to verify the password of the encrypted Excel files. For this, you can follow the below steps.
- Load the Excel file using FileStream class.
- To verify the password, use FileFormatUtil.VerifyPassword(FileStream, string) method that returns a bool value.
- If the returned value is true then the password is valid else it is invalid.
The following code sample shows how to verify password of an encrypted Excel file using C#.
Get a Free License
You can get a free temporary license in order to try the API without evaluation limitations.
Conclusion
In this article, you have learned how to encrypt and decrypt Excel files using C# from within .NET applications. Furthermore, you have seen how to verify the password of the encrypted Excel files. You can explore more about the C# Excel automation API using documentation.