Google 工作表 api 追加和更改行的颜色(Node js)

Google Sheets api Append and Change Colour of the row (Node js)

我一直在尝试在追加时格式化工作表行,但无法弄清楚。 附加行没有问题,它工作正常。那么我怎样才能同时追加和格式化该行呢?据我所知,我应该使用“batchUpdate()”函数,我尝试了很多方法,但仍然无法弄清楚。

我相信你的目标如下。

  • 您想在 Google Spreadsheet.
  • 中向 sheet 添加一行
  • 附加行时,您想为该行设置颜色(背景色?)。
  • 您想使用 Node.js 实现此目的。

在这种情况下,下面的示例脚本怎么样?

示例脚本:

在此脚本中,使用了 Node.js 的 googleapis。 Ref This can be used with Quickstart. Ref

const sheets = google.sheets({ version: "v4", auth }); // Please use your authorization script.

const spreadsheetId = "###"; // Please set your Spreadsheet ID.
const sheetId = "0"; // Please set your sheet ID.
const appendValue = ["sample1", "sample2", "sample3"]; // This is a sample append value.
const backgroundColor = { red: 1, green: 0, blue: 0 }; // This is a sample background color. In this case, the red color is used.

const values = appendValue.map((e) => ({userEnteredValue: { stringValue: e }, userEnteredFormat: { backgroundColor }}));
const requests = [{appendCells: {rows: [{ values }], sheetId, fields: "userEnteredValue,userEnteredFormat"}}];
await sheets.spreadsheets.batchUpdate({spreadsheetId, resource: { requests }});
  • 当此脚本为运行时,"sample1", "sample2", "sample3"行附加到sheet,附加行单元格的背景颜色设置为红色.

注:

  • 这是一个简单的示例脚本。所以,请根据您的实际情况进行修改。

参考文献: