ExcelWorksheet Protection

Following sample demonstrates how to protect a worksheet.

Note that specifying advanced settings like sheet password or allowing some objects to be editable is supported only for XLSX file format.

Screenshot

Sheet Protection Screenshot

See the full code below, use RUN EXAMPLE to execute.


1using GemBox.Spreadsheet;
2using System.IO;
3
4class Sample
5{
6    [STAThread]
7    static void Main(string[] args)
8    {
9        // If using Professional version, put your serial key below.
10        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
11
12        ExcelFile ef = new ExcelFile();
13        ExcelWorksheet ws = ef.Worksheets.Add("Sheet Protection");
14
15        ws.Cells[0, 2].Value = "Only cells from A1 to A10 are editable.";
16
17        for (int i = 0; i < 10; i++)
18        {
19            var cell = ws.Cells[i, 0];
20            cell.SetValue(i);
21            cell.Style.Locked = false;
22        }
23
24        ws.Protected = true;
25
26        // ProtectionSettings class is supported only for XLSX file format.
27        ws.Cells[2, 2].Value = "Inserting columns is allowed (only supported for XLSX file format).";
28        var protectionSettings = ws.ProtectionSettings;
29        protectionSettings.AllowInsertingColumns = true;
30
31        ws.Cells[3, 2].Value = "Sheet password is 123 (only supported for XLSX file format).";
32        protectionSettings.SetPassword("123");
33
34        ef.Save("Sheet Protection.xls");
35    }
36}
1Imports GemBox.Spreadsheet
2Imports System.IO
3
4Module Samples
5
6    Sub Main()
7
8        ' If using Professional version, put your serial key below.
9        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY")
10
11        Dim ef As ExcelFile = New ExcelFile
12        Dim ws As ExcelWorksheet = ef.Worksheets.Add("Sheet Protection")
13
14        ws.Cells(0, 2).Value = "Only cells from A1 to A10 are editable."
15
16        For i = 0 To 9 Step 1
17
18            Dim cell = ws.Cells(i, 0)
19            cell.SetValue(i)
20            cell.Style.Locked = False
21
22        Next
23
24        ws.Protected = True
25
26        ' ProtectionSettings class is supported only for XLSX file format.
27        ws.Cells(2, 2).Value = "Inserting columns is allowed (only supported for XLSX file format)."
28        Dim protectionSettings = ws.ProtectionSettings
29        protectionSettings.AllowInsertingColumns = True
30
31        ws.Cells(3, 2).Value = "Sheet password is 123 (only supported for XLSX file format)."
32        protectionSettings.SetPassword("123")
33
34        ef.Save("Sheet Protection.xls")
35
36    End Sub
37
38End Module

Check next sample or find out more about GemBox.Spreadsheet and GemBox Software.