我正在使用 Google Sheets 客户端库在电子表格中插入新行,然后在顶行(但在标题行下方)写入一些数据。
batchUpdate 方法应该允许使用它的人以一种方式组合操作,如果一个操作失败,其他操作也将失败。这对我来说是最好的,因为我不想在第 2 行插入数据,除非我首先在顶部成功插入了新行。
但是,我不太了解如何正确使用 API 的一些事情。结果是在顶部插入了一个新行,但只有一个数据点写入第一个单元格,而不是该行中的所有 5 个单元格。这是 API 调用:
const sheets = google.sheets({ version: 'v4', auth });
sheets.spreadsheets.batchUpdate({
spreadsheetId: SHEET_ID,
"resource": {
"requests": [
{
"insertDimension": {
"range": {
"sheetId": 0,
"dimension": "ROWS",
"startIndex": 1,
"endIndex": 2
},
"inheritFromBefore": false
}
},
{
"updateCells": {
"rows":
{
values: [{
"userEnteredValue": {
stringValue: "Dec 14-Sep 20"
},
"userEnteredValue": {
numberValue: 10
},
"userEnteredValue": {
numberValue: 5
},
"userEnteredValue": {
numberValue: 1
},
"userEnteredValue": {
numberValue: 0.2
},
}]
}
,
"fields": "*",
// "start": {
// "sheetId": 0,
// "rowIndex": 1,
// "columnIndex": 4
// },
"range": {
"sheetId": 0,
"startRowIndex": 1, // I want to write to second row only
"endRowIndex": 2,
"startColumnIndex": 0, // start at first column
"endColumnIndex": 5 // end at 5th column
}
}
}
]
}
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
} else {
console.log('No data found.');
}
});
正如你所看到的,我指定了一个范围,但是数据;具体来说,数据数组中的最后一个值 0.2 正在写入工作表中的第一列。我还尝试使用“开始”GridCoordinate 而不是“范围”GridRange,但结果是相同的。
我需要修改什么才能将该数据数组中的所有 5 个值一次写入一行、一列到工作表中?
最佳答案
问题不在于开始或范围属性;相反,问题在于传递到 rows 数组的对象格式不正确。
现在,Google 确实使使用 batchUpdate 修改单元格的 API 变得相当复杂。首先,在 UpdateCellsRequest 的文档中我们看到 rows[] 数组采用 RowData目的。 RowData 是一个具有键“values”的对象,其中包含一组 CellData 对象,但每个 CellData 对象都必须封装在一组 {}
中。
CellData 对象由一个或多个属性组成,在本例中我们选择“userEnteredValue”。这包含 ExtendedValue对象,可以是数字、字符串、 bool 值、公式或错误,它是这个复杂的嵌套对象系列中的最后一个。
上面代码的问题在于,rows属性在文档中被标记为数组,但它实际上是一个包含数组的对象;因此,您在“行”之后缺少大括号。
这是你应该拥有的:
{
"updateCells": {
"rows":
{
values: [
{
"userEnteredValue": {
stringValue: "Dec 14-Sep 20"
}
},
{
"userEnteredValue": {
numberValue: 10
}
},
{
"userEnteredValue": {
numberValue: 5
}
},
{
"userEnteredValue": {
numberValue: 1
}
},
{
"userEnteredValue": {
numberValue: 0.2
}
}
]
}
,
"fields": "*",
"range": {
"sheetId": 0,
"startRowIndex": 1,
"endRowIndex": 2,
"startColumnIndex": 0,
"endColumnIndex": 5
}
}
}
关于node.js - 如何使用batchUpdate在顶部插入一个新行,然后插入5个数据单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57557120/