google-电子表格node.js。复制并粘贴范围内的单元格

问题描述 投票:0回答:1

那里!我有两个单元格范围 BM4:BM29BN4:BN29。我需要从第一个范围复制单元格值并粘贴到另一个范围。第一个区域中的单元格具有将表中其他单元格中的数字相加的公式。我需要复制这个数字并粘贴到其他范围中。

我正在使用:https://www.npmjs.com/package/google-spreadsheet/v/4.1.0

为了进行身份验证,我使用:

const { GoogleSpreadsheet } = require('google-spreadsheet');
const { JWT } = require('google-auth-library');
require("dotenv").config();

const serviceAccountAuth = new JWT({
    email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
    key: process.env.GOOGLE_PRIVATE_KEY,
    scopes: [
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive'
    ],
});
const doc = new GoogleSpreadsheet(process.env.SPREADSHEET_TABLE_ID, serviceAccountAuth);

module.exports = { doc };

我尝试了很多不同的方法,但都没有产生任何结果。

await doc.loadInfo();
const sheet = doc.sheetsById[SOME_SHEET_ID];
await sheet.loadCells();

sheet.loadCellsInRange()
sheet.copyPaste()
sheet.getCellByA1()

https://i.stack.imgur.com/Ms4hP.png https://i.stack.imgur.com/kZdC3.png

javascript node.js node-modules google-sheets-api
1个回答
0
投票

从您的以下回复来看,

我用公式添加了表格中的屏幕截图。我需要将 BM 列中的值复制到 BN 列

既然如此,下面的修改如何?在此修改中,使用batchUpdate 方法将“BM”列的值复制到“BN”列。不幸的是,我在google-spreadsheet中找不到batchUpdate方法。因此,我直接使用

https
模块请求 Sheets API。访问令牌和电子表格 ID 分别从脚本中的
doc
检索。请修改如下。

来自:

await doc.loadInfo();
const sheet = doc.sheetsById[SOME_SHEET_ID];
await sheet.loadCells();

sheet.loadCellsInRange()
sheet.copyPaste()
sheet.getCellByA1()

致:

请设置您的工作表ID。

const https = require("https");

const sheetId = 12345678; // Please set your sheet ID.

const srcStartColumnIndex = 64; // Column "BM"
const dstStartColumnIndex = 65; // Column "BN"

const url = `https://sheets.googleapis.com/v4/spreadsheets/${doc.spreadsheetId}:batchUpdate`;
const options = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + doc.jwtClient.gtoken.rawToken.access_token,
  },
};
const postData = {
  requests: [
    {
      copyPaste: {
        source: { sheetId, startRowIndex: 0, startColumnIndex: srcStartColumnIndex, endColumnIndex: srcStartColumnIndex + 1 },
        destination: { sheetId, startRowIndex: 0, startColumnIndex: dstStartColumnIndex, endColumnIndex: dstStartColumnIndex + 1 },
        pasteType: "PASTE_VALUES",
      },
    },
  ],
};
const req = https.request(url, options, (res) => {
  const chunks = [];
  res
    .on("data", (chunk) => chunks.push(Buffer.from(chunk)))
    .on("end", () => console.log(Buffer.concat(chunks).toString()));
});
req.write(JSON.stringify(postData));
req.on("error", (err) => console.log(err));
req.end();
  • 通过此修改,当运行此脚本时,通过一次 API 调用,使用 batchUpdate 方法将列“BM”的值复制到列“BN”。在这种情况下,仅复制值。

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.