首页 > 解决方案 > 使用nodejs google sheet api将背景颜色从一列复制到另一列

问题描述

我正在尝试将背景颜色从已经具有条件格式的一列复制到另一列,以便两个列单元格具有相同的背景颜色,即使它们具有不同的数据。

我发现这个 php 文档具有获取和设置背景: https ://developers.google.com/resources/api-libraries/documentation/sheets/v4/php/latest/class-Google_Service_Sheets_CellFormat.html

但是找不到关于如何使用 node.js 格式化这个请求的大量信息。不确定节点中是否存在获取和设置背景? https://github.com/googleapis/google-api-nodejs-client/tree/master/samples/sheets

我的计划是从格式化的列中获取背景颜色,然后将该格式复制到没有格式化的列中。我真的找不到任何关于 Node.js 的文档。有没有?这甚至可以通过 batchUpdate 请求实现吗?

函数 getFormatting(sheetId, startRowIndex, endRowIndex, columns, column) { const function_name = 'getFormatting';

let { startColumnIndex, endColumnIndex } = getStartEndIndex(columns, column, column);

const request =  [{
  "getBackgroundColor": {
          "backgroundColorRange": {
          "range": {
            sheetId,
            startRowIndex,
            endRowIndex,
            startColumnIndex,
            endColumnIndex,
          }, }
  }
}];

}

我希望获得 A1:A1(length) 列的背景颜色,并将其复制到 B1:B1(length) 中的顺序完全相同

标签: google-sheets-api

解决方案


  • 您想将“A”列中单元格的背景颜色复制到“B”列。
  • 您想使用 googleapis 和 Node.js 来实现这一点。
  • 您已经能够使用 Sheets API 获取和放置电子表格的值。

我可以像上面那样理解。如果我的理解是正确的,这个答案怎么样?请认为这只是几个答案之一。

流动:

该脚本的流程如下。

  1. 使用 检索“A”列中单元格的背景颜色spreadsheets.get()
  2. 使用检索到的值创建请求正文。
  3. 使用 更改“B”列中单元格的背景颜色spreadsheets.batchUpdate()

示例脚本:

使用前,请先设置 和 的spreadsheetId变量sheetName

const sheets = google.sheets({ version: "v4", auth });

const spreadsheetId = "###"; // Please set the Spreadsheet ID.
const sheetName = "Sheet1"; // Please set the sheet name. In this sample, "Sheet1" is set.

const request = {
  spreadsheetId: spreadsheetId,
  ranges: [`${sheetName}!A1:A`],
  fields: "sheets"
};
sheets.spreadsheets.get(request, function(err, response) {
  if (err) {
    console.error(err);
    return;
  }
  let requests = {
    requests: [
      {
        updateCells: {
          fields: "userEnteredFormat.backgroundColor",
          start: {
            sheetId: response.data.sheets[0].properties.sheetId,
            rowIndex: 0,
            columnIndex: 1
          },
          rows: response.data.sheets[0].data[0].rowData.map(function(row) {
            return {
              values: [
                {
                  userEnteredFormat: {
                    backgroundColor:
                      row.values[0].effectiveFormat.backgroundColor
                  }
                }
              ]
            };
          })
        }
      }
    ]
  };
  sheets.spreadsheets.batchUpdate(
    { spreadsheetId: spreadsheetId, requestBody: requests },
    function(err, response) {
      if (err) {
        console.error(err);
        return;
      }
      console.log(JSON.stringify(response.data, null, 2));
    }
  );
});

参考:


推荐阅读