set cell value google script
func setCellValue(sheet *sheets.Service, spreadsheetID, sheetName, cell string, value interface{}) error {
valueRange := sheets.ValueRange{
Values: [][]interface{}{{value}},
}
_, err := sheet.Spreadsheets.Values.Update(spreadsheetID, sheetName+"!"+cell, &valueRange).
ValueInputOption("RAW").
Do()
if err != nil {
return err
}
return nil
}
Explanation:
- The function
setCellValue
takes the following parameters: sheet
: Represents the Google Sheets service.spreadsheetID
: ID of the spreadsheet where the cell exists.sheetName
: Name of the sheet where the cell exists.cell
: The specific cell to update (e.g., "A1", "B2").value
: The value to set in the specified cell.valueRange
is a variable of typesheets.ValueRange
that holds the new value to be set. It's formatted as a two-dimensional slice (2D array) containing a single element (the value to set) within another array. This structure is required by the Sheets API for value updates.The
sheet.Spreadsheets.Values.Update
method updates the value in the specified cell within the spreadsheet. It takes thespreadsheetID
,sheetName+"!"+cell
(the specific cell in A1 notation), and thevalueRange
containing the new value.ValueInputOption("RAW")
specifies that the input value should be treated as raw text and not be parsed or evaluated as a formula.Do()
executes the update operation.The function returns an error if any issues occur during the update process; otherwise, it returns
nil
to indicate success.