Protect and Unprotect Worksheets

VSTO

// Instantiate the Application object.
Excel.Application excelApp = Application;

// Excel.Application excelApp = Application;

// Specify the template Excel file path.
string myPath = "Protect and unProtect Worksheets.xlsx";

// Open the Excel file.
excelApp.Workbooks.Open(myPath, Missing.Value, Missing.Value,
    Missing.Value, Missing.Value,
    Missing.Value, Missing.Value,
    Missing.Value, Missing.Value,
    Missing.Value, Missing.Value,
    Missing.Value, Missing.Value,
    Missing.Value, Missing.Value);

// Protect the worksheet specifying a password with Structure and Windows attributes.
((Excel.Worksheet)excelApp.ActiveSheet).Protect("thispassword",
    missing, missing, missing, missing, missing, missing, missing, missing,
    missing, missing, missing, missing, true, missing, missing);

// Unprotect the worksheet specifying its password.
((Excel.Worksheet)excelApp.ActiveSheet).Unprotect("thispassword");

// Save the file.
excelApp.ActiveWorkbook.Save();

// Quit the Application.
excelApp.Quit();

Aspose.Cells

// Specify the template Excel file path.
string myPath = "Protect and unProtect Worksheets.xlsx";

// Instantiate a new Workbook.
Workbook workbook = new Workbook(myPath);

// Protect the worksheet specifying a password with Structure and Windows attributes.
workbook.Worksheets[workbook.Worksheets.ActiveSheetIndex].Protect(ProtectionType.All, "thispassword", "");

// Unprotect the worksheet specifying its password.
workbook.Worksheets[workbook.Worksheets.ActiveSheetIndex].Unprotect("thispassword");

// Save the Excel file.
workbook.Save(myPath);

Download Sample Code

  • Github
  • Sourceforge
  • Bitbucket