【问题标题】:Nodejs Google Sheets APINodejs 谷歌表格 API
【发布时间】:2017-06-11 04:16:20
【问题描述】:

有谁知道在哪里可以找到使用 Google Sheets API 写入 google sheet 的好例子?我使用了https://developers.google.com/sheets/api/quickstart/nodejs,并且成功地能够从 Google 表格中读取数据,但在弄清楚如何写入 Google 表格时遇到了麻烦。

【问题讨论】:

  • @Avraham 在墙后

标签: node.js google-sheets-api


【解决方案1】:

假设您已经获得授权的 oAuth2Client,以下内容适用于我。

const { google } = require('googleapis');
const sheets = google.sheets({ version: 'v4', oAuth2Client});

async function writeSample() {
  let title = "NewSpreadsheet";
  try {
    var spreadsheet = await createSheet(title);
    console.log(`Spreadsheet ID: ${spreadsheet.spreadsheetId}`);

    range = "Sheet1!A1:D5";
    let valueInputOption = "RAW";
    values = [
      ["Item", "Cost", "Stocked", "Ship Date"],
      ["Wheel", "$20.50", "4", "3/1/2016"],
      ["Door", "$15", "2", "3/15/2016"],
      ["Engine", "$100", "1", "30/20/2016"],
      ["Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)"]
    ];
    var result = await writeSheet(spreadsheet.spreadsheetId, range, valueInputOption, values);
    console.log('%d cells updated.', result.updatedCells);
    return result;
  }
  catch (error) {
    console.log(error);
  }
}

async function createSheet(title) {
  var resource = {
    properties: {
      title
    },
  };
  return sheets.spreadsheets.create({ resource, fields: 'spreadsheetId', })
    .then(response => response.data);
}

async function writeSheet(spreadsheetId, range, valueInputOption, values, ) {
  resource = {
    values
  };
  return sheets.spreadsheets.values.update({ spreadsheetId, range, valueInputOption, resource, })
    .then(response => response.data);
}

【讨论】:

    【解决方案2】:

    Sheets API 在 google sheet 上有关于 Writing a single range 的示例。有些概念你必须理解,比如A1 Notation

    除了指南中的示例之外,我还编写了 JS 代码来演示在 SO thread 上的工作表上的书写。这将很有帮助,因为 NodejS 也使用 JS。

    【讨论】:

    • access_token和quickstart.js生成的token一样吗?我尝试按照您的示例使用该访问令牌。我的代码运行良好,但没有任何内容写入 Google 表格。
    【解决方案3】:

    是的,我还阅读了 noogui 的参考资料:您需要一些时间才能完成程序。

    但是我已经成功完成了以下功能:

        appedData ()
        deleteRow () (I can post them if you wish)
    

    我需要连续插入:温度、湿度和压力,并组合删除最旧的行(第 1 行)。 我将这两个函数放在 listMajors(...) 最初所在的同一行中(在快速入门,js 中)。然后将其放入循环中: 馊主意: 这些函数是异步的,所以你不知道一个完成,另一个开始, console.log() 打印显示:

     appedData ()
     deleteRow ()
     appedData ()
     deleteRow ()
     deleteRow ()
     appedData ()
     deleteRow ()
     appedData ()
     appedData ()
    

    所以有时appedData() 和deleteRow() 按实际顺序排列,有时两次或多次appedData() 按顺序排列 其他时间按顺序两次或多次 deleteRow()。

    因此,我将 quickstart.js 更改为同步函数而不是异步函数: 我删除了用fs.readFileSync 替换fs.readFile 的回调, 它似乎有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多