Back to Devexpress

Use the Excel Export API to Password Protect a Workbook

officefileapi-118446-excel-export-library-workbooks-how-to-password-protect-a-workbook.md

latest2.2 KB
Original Source

Use the Excel Export API to Password Protect a Workbook

  • Sep 19, 2023
  • 2 minutes to read

The example below demonstrates how to encrypt a workbook and set a password to open it. To specify encryption options, create an instance of the EncryptionOptions class and pass it as a parameter to the IXlExporter.CreateDocument method.

View Example

csharp
// Create an exporter instance.
IXlExporter exporter = XlExport.CreateExporter(documentFormat);

// Specify encryption options. 
// A workbook will be encrypted using the default encryption mechanism
// (agile encryption for XLSX files, and RC4 encryption for XLS files).
EncryptionOptions encryptionOptions = new EncryptionOptions();
// Specify the encryption password.
encryptionOptions.Password = "password";

// Create a new document and encrypt its contents.
using (IXlDocument document = exporter.CreateDocument(stream, encryptionOptions))
{
    // Specify the document culture. 
    document.Options.Culture = CultureInfo.CurrentCulture;
}
vb
' Create an exporter instance.
Dim exporter As IXlExporter = XlExport.CreateExporter(documentFormat)

' Specify encryption options. 
' A workbook will be encrypted using the default encryption mechanism
' (agile encryption for XLSX files, and RC4 encryption for XLS files).
Dim encryptionOptions As New EncryptionOptions()
' Specify the encryption password.
encryptionOptions.Password = "password"

' Create a new document and encrypt its contents.
Using document As IXlDocument = exporter.CreateDocument(stream, encryptionOptions)
    ' Specify the document culture. 
    document.Options.Culture = CultureInfo.CurrentCulture
End Using

When end-users open the encrypted document in Microsoft® Excel®, the following dialog prompts them for a password: