如何使用 NodeJs 将 JavaScript 对象导出到 Google Sheet

Bla*_*tus 3 javascript google-api google-sheets node.js google-sheets-api

我有一个像这样的 JavaScript 对象

[{ a: "123", b: "456" }, { a: "321", b: "654" }]
Run Code Online (Sandbox Code Playgroud)

有没有办法使用 NodeJs 将其导出到 Google Sheet

在此输入图像描述

Tan*_*ike 9

我相信您的目标如下。

  • 你想把值[{ a: "123", b: "456" }, { a: "321", b: "654" }]使用 Node.js 将 的值放入电子表格中。

在这种情况下,如何使用在这种情况下,使用google-spreadsheet

用法:

1. 安装谷歌电子表格。

你可以在这里看到它

2、授权

我认为在这种情况下,服务帐户可能会有用。

您可以在这里查看授权方法

3. 示例脚本:

const { GoogleSpreadsheet } = require("google-spreadsheet");

const creds = require("credential.json"); // Please set your credential file.

const doc = new GoogleSpreadsheet("##"); // Please set your Spreadsheet ID.

const sample = async () => {
  await doc.useServiceAccountAuth(creds);
  await doc.loadInfo();
  const worksheet = doc.sheetsByIndex[0]; // Here, 1st tab on Google Spreadsheet is used.

  // This is from your sample value.
  const values = [
    { a: "123", b: "456" },
    { a: "321", b: "654" },
  ];
  await worksheet.setHeaderRow(["a", "b"]); // This is the header row.
  await worksheet.addRows(values); // Your value is put to the sheet.
};

sample();
Run Code Online (Sandbox Code Playgroud)
  • 运行此脚本时,将获得示例图像中的结果。

参考: