Skip to main content

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

How to: Write-Protect a Workbook

  • 2 minutes to read

Use the Workbook.DocumentSettings.WriteProtection property to return write-protection options for a document.

#Make a Workbook Read-Only

Enable the WriteProtectionOptions.ReadOnlyRecommended option to make a workbook read-only.

using(var workbook = new Workbook())
{
    var wpOptions = workbook.DocumentSettings.WriteProtection;
    wpOptions.ReadOnlyRecommended = true;
    workbook.SaveDocument("WriteProtectedDocument.xlsx");
}

When users open this workbook in Microsoft® Excel®, it prompts them to open the document as read-only.

Read-only workbook

#Specify a Password To Modify a Workbook

Call the WriteProtectionOptions.SetPassword method to specify a password to prevent modifications from unauthorized users.

using(var workbook = new Workbook())
{
    var wpOptions = workbook.DocumentSettings.WriteProtection;
    wpOptions.SetPassword("Password");
    wpOptions.UserName = "John Smith";
    workbook.SaveDocument("WriteProtectedDocument.xlsx");
}

When users open this workbook in Microsoft® Excel®, it prompts them to enter a password to modify the document.

Write-protection options for a workbook

#Clear a Password Used to Modify a Workbook

The following code snippet uses the WriteProtectionOptions.CheckPassword method to check a given password. If the password is valid, WriteProtectionOptions.ClearPassword is called to remove write-protection from a workbook.

using (Workbook workbook = new Workbook())
{
    workbook.LoadDocument("WriteProtectedDocument.xlsx");
    RemoveWriteProtection(workbook, "password");
}
// ...

private void RemoveWriteProtection(Workbook workbook, string password)
{
    var wpOptions = workbook.DocumentSettings.WriteProtection;
    if (wpOptions.IsPasswordProtected && wpOptions.CheckPassword(password))
        wpOptions.ClearPassword();
    else
    {
        Console.WriteLine("The file is not write-protected or the specified password is invalid!");
        Console.ReadKey();
    }
}