尝试使用UpdateCellsRequest更新单元格范围的格式,但仅更新该范围中的第一个单元格。
let fixFormats = () => {
return new Promise((resolve, reject) => {
var sheets = google.sheets('v4');
var options = {
auth: auth,
spreadsheetId: spreadsheetId,
resource: {
requests: [{
updateCells: {
range: {
sheetId: 0,
startColumnIndex: 0,
endColumnIndex: 2,
},
rows: [{
values: {
userEnteredFormat: {
numberFormat: {
type: "CURRENCY",
pattern: "$#,##0.00"
}
}
}
}],
fields: "userEnteredFormat.numberFormat",
}
}]
}
}
sheets.spreadsheets.batchUpdate(options, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
console.log(res);
}
});
});
}
根据这篇文章,这应该是可能的。我已经阅读了参考文档,并确认我的请求格式正确。特别注意范围的定义。
编辑:从startColumnIndex(包括)和endColumnIndex(排除)的更令人困惑的行为。
而sheetId:0,startColumnIndex:0,endColumnIndex:2例如仅更新单元格A1 ...而sheetId:0,startColumnIndex:0,endColumnIndex:3相同。
但是...如果sheetId:0,startColumnIndex:1,endColumnIndex:2然后仅更新列B(colIndex:1)...
这是一个错误还是我错过了什么?
编辑:按要求输出...虽然不确定此显示正确的响应。
{ spreadsheetId: '<mysheet>',
replies: [ {} ],
updatedSpreadsheet:
{ spreadsheetId: '<mysheet>',
properties:
{ title: 'OLR',
locale: 'en_US',
autoRecalc: 'ON_CHANGE',
timeZone: 'America/Los_Angeles',
defaultFormat: [Object] },
sheets: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
namedRanges: [ [Object] ],
spreadsheetUrl: 'https://docs.google.com/a/company.com/spreadsheets/d/<mysheet>/edit' } }
如果我用JSON.stringify响应,它将给出看起来范围内的每个单元格的格式,这是很多单元格。不过,在选择的3列中,第一列中的第一个单元格被更新,但其余部分保持不变。
弄清楚了!尽管我可以通过使用'repeatCells'函数而不是'updateCells'使其工作,但我不确定为什么这不起作用,因为这似乎是该函数的预期目的。我将不得不再读一遍,但是为了后代,更新的代码起作用了:
var options = {
auth: auth,
spreadsheetId: spreadsheetId,
resource: {
requests: [{
repeatCell: {
fields: "userEnteredFormat.numberFormat",
range: {
sheetId: 1564685276,
startColumnIndex: 1, // inclusive
endColumnIndex: 3, // exclusive
},
cell: {
userEnteredFormat: {
numberFormat: {
type: "CURRENCY",
pattern: "$#,##0.00"
}
}
}
}
}],
}
}
gh ...此外,我并没有完全确信这确实有效,因为我发现我要测试的单元格是正常数值。在我的真实电子表格上,由于从PostgreSQL数据库导入结果时添加了奇数的前撇号,因此无法正常工作。我编写了一个函数来替换这些函数,然后执行格式化,一切都变得笨拙了。
@Priya-电子表格ID在我的代码的其他地方定义。您可以在电子表格的网址中找到它。(长字母数字字符串)
所以这很奇怪,我来自batchUpdate updateCells,它只会更新一列