Encrypt Decrypt Excel Files

Microsoft Excel offers a robust encryption feature that protects workbook data from unauthorized users. By assigning a password, you control who can open and edit the file. In this article we demonstrate how to encrypt, decrypt, and validate passwords for Excel workbooks using C# with the Aspose.Cells for .NET library.

C# API to Encrypt or Decrypt Excel Files

To work with encryption and decryption, we use the Aspose.Cells for .NET API. This library mirrors the encryption options available in Microsoft Excel and provides a straightforward programming model. You can either download the library or add it to your project via NuGet.

Install-Package Aspose.Cells

Encrypt Excel Files using C#

Aspose.Cells supports both SHA and AES encryption algorithms, matching the security levels used by recent Excel versions. For legacy Excel 2003 files you can also select older encryption methods:

  • XOR
  • Compatible (Office 97/2000 compatible)
  • Enhanced Cryptographic Provider V1
  • Strong Cryptographic Provider

Steps to encrypt a workbook

  1. Load the workbook with the Workbook class.
  2. Call Workbook.SetEncryptionOptions(EncryptionType, int) to choose the encryption algorithm and key size.
  3. Assign a password through Workbook.Settings.Password.
  4. Save the encrypted file using Workbook.Save(string).

The code snippet below demonstrates these steps in C#.

Decrypt Excel Files using C#

Decrypting a protected workbook is equally simple. Follow these actions:

  1. Instantiate Workbook with the file path and the password used during encryption.
  2. Reset the password by setting Workbook.Settings.Password to null.
  3. Save the workbook to a new location or overwrite the original file.

The following example shows how to remove encryption from an Excel file using C#.

Verify Password of Encrypted Excel File using C#

Before attempting to open an encrypted workbook, you may want to confirm that a supplied password is correct. Aspose.Cells provides a utility method for this purpose.

Verification process

  1. Open the file as a FileStream.
  2. Call FileFormatUtil.VerifyPassword(FileStream, string) – it returns true if the password matches, otherwise false.

The sample code below illustrates password verification in C#.

Get a Free License

You can get a free temporary license to evaluate the API without any evaluation restrictions.

Conclusion

This guide covered how to encrypt, decrypt, and verify passwords for Excel workbooks using C# and the Aspose.Cells for .NET API. With these techniques you can securely manage Excel files in any .NET application. For additional examples and detailed documentation, explore the official documentation.

See Also