Skip to main content

Use the Excel Export API to Password Protect a Workbook

  • 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

// 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;

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