Looking to provide a request object to BatchUpdate so both cell values and formatting can be updated. I am constructing the following request object:
const request = [{
updateCells: {
range: {
sheetId:grid.sheetId,
startRowIndex: grid.startRow,
endRowIndex: grid.endRow,
startColumnIndex: grid.startCol,
endColumnIndex:grid.endCol
},
rows: [
{
values: [
{
userEnteredFormat: {
backgroundColor: {
red: 1,
green: 0.4,
blue: 0.4
}
},
userEnteredValue: {
stringValue: {object containing the row}
}
}
]
}
],
fields: "userEnteredFormat,userEnteredValue"
}
}];
Apparently I get an error "Starting an object on a scalar field". Is there some different request type to be made to provide the row as an array or object? Looking at the docs [https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#RowData], it doesn't look like it.
TIA
CodePudding user response:
Although unfortunately, I'm not sure whether I could correctly understand {object containing the row}
of stringValue: {object containing the row}
, in your request body, if {object containing the row}
of stringValue: {object containing the row}
is an object like {key: "value"}, an error like
starting an object on a scalar fieldoccurs. I thought that this might be the reason for your current issue. And also, when an array like
["sample value"]is used, an error like
Proto field is not repeating, cannot start listoccurs. In this case, please use a string value like
stringValue: "sample value"`. Please be careful about this.
From your question of Is there some different request type to be made to provide the row as an array or object?
, if you want to use an array including values to this request body, how about the following modification?
Modified script:
function myFunction() {
const spreadsheetId = "###"; // Please set your Spreadsheet ID.
const grid = { sheetId: 0, startRow: 0, startCol: 0 }; // Please set your gridrange.
const values = [["sample value1", "sample value2"], ["sample value3", "sample value4"]]; // Please set your values as 2 dimensional array.
const request = [{
updateCells: {
range: {
sheetId: grid.sheetId,
startRowIndex: grid.startRow,
startColumnIndex: grid.startCol,
},
rows: values.map(r => ({
values: r.map(c => ({
userEnteredFormat: { backgroundColor: { red: 1, green: 0.4, blue: 0.4 } },
userEnteredValue: { stringValue: c }
}))
})),
fields: "userEnteredFormat,userEnteredValue"
}
}];
Sheets.Spreadsheets.batchUpdate({ requests: request }, spreadsheetId);
}
When this script is run,
values
are put from the cell "A1" insheetId
.About
grid
, in this case, I think that when the start cell coordinate (the top left side) is put, this script can be used.
Note:
- This is a simple sample script for using an array. So, if your
values
include numbers, boolean, and formulas, please use the keys ofnumberValue
,boolValue
andformulaValue
. Please be careful about this. And, if you are using a JSON object, when you convert it to a 2-dimensional array, you can use it using this script.