Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To edit ranges in a protected sheet using Golang excelize, you can use the SetSheetProtection function. This function allows you to set various sheet protection options including allowing the user to edit specific ranges.

Here's an example code snippet that sets a protected sheet and allows editing of a specific range:

package main

import (
    "fmt"
    "github.com/360EntSecGroup-Skylar/excelize"
)

func main() {
    // Create a new XLSX file with a single sheet
    file := excelize.NewFile()
    sheetName := "Sheet1"

    // Set the data to be protected
    dataRange := "A1:B10"
    file.SetSheetRow(sheetName, "A1", &[]string{"Name", "Age"})
    file.SetSheetRow(sheetName, "A2", &[]interface{}{"John", 25})
    file.SetSheetRow(sheetName, "A3", &[]interface{}{"Jane", 27})

    // Set the sheet protection and allow editing of the data range
    password := "mypassword"
    file.SetSheetProtection(sheetName, "password", excelize.FormatCellProtection{
        Sheet:           true,
        Objects:         false,
        Scenarios:       false,
        FormatCells:     false,
        FormatColumns:   false,
        FormatRows:      false,
        InsertColumns:   false,
        InsertRows:      false,
        InsertHyperlinks: false,
        DeleteColumns:   false,
        DeleteRows:      false,
        SelectLockedCells: true,
        Sort:            true,
        AutoFilter:      true,
        PivotTables:     true,
        SelectUnlockedCells: true,
        EditObjects:     false,
        EditScenarios:   false,
    }, excelize.FormatCellProtection{
        RangeAddress:    dataRange,
        SelectLockedCells: false,
        SelectUnlockedCells: true,
        FormatCells:     true,
        FormatColumns:   true,
        FormatRows:      true,
        InsertColumns:   true,
        InsertRows:      true,
        InsertHyperlinks: true,
        DeleteColumns:   true,
        DeleteRows:      true,
        EditObjects:     true,
        EditScenarios:   true,
    })

    // Save the file
    err := file.SaveAs("ProtectedSheet.xlsx")
    if err != nil {
        fmt.Println("Error saving file:", err)
        return
    }

    fmt.Println("File saved successfully.")
}

In this example, the SetSheetProtection function is used to set the sheet protection options for the sheet named "Sheet1". The first protection parameter passed is used to set the password, while the second protection parameter is used to allow editing of the data range "A1:B10".

Note that the SelectUnlockedCells option must be set to true in order to allow editing of the specified range.