Other API Samples

Live SpreadsheetGear API Samples

Worksheet Samples Worksheet Protection

Demonstrates various options available when enabling and disabling worksheet protection.

// Create a workbook and local variable to worksheet to do work on.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.ActiveWorksheet;

// The Protect(...) method provides full control over the various options you can use
// to protect a worksheet.  You can provide an optional first parameter for the 
// worksheet password.  All additional parameters are also optional, and are setup 
// below using their default values. 
worksheet.Protect(
    password: "MyPassword1234", 
    protectDrawingObjects: true,
    protectContents: true,
    protectScenarios: true,
    userInterfaceOnly: false,
    allowFormattingCells: false,
    allowFormattingColumns: false,
    allowFormattingRows: false,
    allowInsertingColumns: false,
    allowInsertingRows: false,
    allowInsertingHyperlinks: false,
    allowDeletingColumns: false,
    allowDeletingRows: false,
    allowSorting: false,
    allowFiltering: false,
    allowUsingPivotTables: false
);

// Unprotect a worksheet with a password.
worksheet.Unprotect("MyPassword1234");

// Enable this property to allow programmatic changes to still be made to a 
// worksheet even when worksheet protection is enabled.  UI protection is still 
// enforced.
worksheet.ProtectionMode = true;

// Enables worksheet protection but without a password.
worksheet.ProtectContents = true;

// Only allow unlocked cells to be selected
worksheet.EnableSelection = EnableSelection.UnlockedCells;

// Use the IProtection interface to modify various aspects of a worksheet that 
// should be protected instead of using the above IWorksheet.Protect(...) arguments.
// Please see documentation for a full list of available properties.
SpreadsheetGear.IProtection protectOptions = worksheet.Protection;
protectOptions.AllowSorting = true;
protectOptions.AllowFiltering = true;