那里!我有两个单元格范围 BM4:BM29 和 BN4: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()
从您的以下回复来看,
我用公式添加了表格中的屏幕截图。我需要将 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();