Back to Devexpress

How to: Protect a Workbook

officefileapi-113747-spreadsheet-document-api-examples-protection-how-to-protect-a-workbook.md

latest3.2 KB
Original Source

How to: Protect a Workbook

  • Sep 19, 2023
  • 2 minutes to read

The example below demonstrates how to protect an entire workbook by using the Workbook.Protect method. Workbook protection prevents end-users from modifying a workbook structure (by moving, deleting, adding, renaming, or hiding existing worksheets, or displaying hidden sheets).

View Example

csharp
Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;

// Protect workbook structure with a password (prevent users from adding or
// deleting worksheets or displaying hidden worksheets).
if (!workbook.IsProtected)
    workbook.Protect("password", true, false);
// Add a note.
worksheet["B2"].Value = "Workbook structure is protected with a password. \n You cannot add, move or delete worksheets until protection is removed.";
worksheet.Visible = true;
vb
Dim worksheet As Worksheet = workbook.Worksheets("ProtectionSample")
workbook.Worksheets.ActiveWorksheet = worksheet

' Protect workbook structure with the password (prevent users from adding or
'deleting worksheets or displaying hidden worksheets).
If Not workbook.IsProtected Then
    workbook.Protect("password", True, False)
End If
' Add a note.
worksheet("B2").Value = "Workbook structure is protected with a password. " & ControlChars.Lf & " You cannot add, move or delete worksheets until protection is removed."
worksheet.Visible = True

Unprotect a Workbook

To remove protection, use the Workbook.Unprotect method.

View Example

csharp
Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;

// Unprotect the workbook (requires the password).
if (workbook.IsProtected)
    workbook.Unprotect("password");
// Add a note.
worksheet["B2"].Value = "Workbook is unprotected. Workheets can be added, moved or deleted.";
worksheet.Visible = true;
vb
Dim worksheet As Worksheet = workbook.Worksheets("ProtectionSample")
workbook.Worksheets.ActiveWorksheet = worksheet

' Unprotect the workbook using a password.
If workbook.IsProtected Then
    workbook.Unprotect("password")
End If
' Add a note.
worksheet("B2").Value = "Workbook is unprotected. Workheets can be added, moved or deleted."
worksheet.Visible = True

See Also

How to: Protect a Worksheet

How to: Protect Specific Worksheet Ranges