Protect a Worksheet with Password

This demo uses the DevExpress Spreadsheet Document API to password-protect worksheets (the password grants access to worksheet modification operations). You can process the sample file or supply your own document. To do the latter, select Upload a File in the file selection drop-down.

Specify the protection password and permitted actions. Select the worksheet to protect in the Protection Settings panel. Use the Protect and Save as... dropdown button to select the output format, protect document worksheets, and download the result.

Sample document
InvestmentPortfolio.xlsx
Select locked cells
Select unlocked cells



using DevExpress.Spreadsheet;

Stream ProtectWorksheetWithPassword(Stream inputStream, DocumentFormat outputFormat, string worksheetPassword,
    bool protectActiveWorksheetOnly, IEnumerable<WorksheetProtectionPermissions> worksheetProtectionPermissions) {
    using var workbook = new Workbook();

    workbook.LoadDocument(inputStream);

    WorksheetProtectionPermissions permissions = 0;
    foreach(WorksheetProtectionPermissions value in worksheetProtectionPermissions)
        permissions |= value;

    var worksheetsToProtect = new List<Worksheet>();
    if(protectActiveWorksheetOnly) {
        var activeSheet = workbook.Worksheets.ActiveWorksheet;
        worksheetsToProtect.Add(activeSheet);
    } else
        worksheetsToProtect = workbook.Worksheets.ToList();

    foreach(var worksheet in worksheetsToProtect) {
        worksheet.Protect(worksheetPassword ?? string.Empty, permissions);
    }

    var outputStream = new MemoryStream();

    workbook.SaveDocument(outputStream, outputFormat);

    outputStream.Position = 0;
    return outputStream;
}