Cell Protection

This guide will show the process of applying cell protection to a spreadsheet cell.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniOffice SDK, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unioffice-examples

To get the example navigate to the path spreadsheet/cell-protection folder in the unioffice-examples directory.

cd unioffice-examples/spreadsheet/cell-protection/

How it works

The import section in lines 14-21, imports the UniOffice packages and other necessary packages of the Go standard library. The init function sets the metered API license key before running the main function. The main function is defined in lines 23-58. In this function in line 24, a new workbook is created using spreadsheet.New(). Then a new spreadsheet.Sheet is created using ss.AddSheet() in line 27. Lines 31-32 create a cell style and set the cell protection setting. Line 34 applies the defined cell style to a range of cells i.e. A1-D10 using:


from, to, err := reference.ParseRangeReference("A1:D10")
if err != nil {
  panic(err)
}
for rowIdx := from.RowIdx; rowIdx <= to.RowIdx; rowIdx++ {
  for colIdx := from.ColumnIdx; colIdx <= to.ColumnIdx; colIdx++ {
    currentCell := reference.IndexToColumn(colIdx)
    sheet.Row(rowIdx).Cell(currentCell).SetStyle(cellStyle1)
  }
}

Then the cell style is applied to column F in lines 44-45. Finally, the protection is added to the sheet, locked and then the file is saved using:

p := sheet.Protection()
sp.LockSheet(true)
// Set password for unlocking sheet.
sp.SetPassword("unioffice")

if err := ss.SaveToFile("cell-protection.xlsx"); err != nil {
  fmt.Println(err)
}

Run the code

Run the following command to create the spreadsheet file.

go run main.go

Got any Questions?

We're here to help you.