首页 > 解决方案 > 使用 Node js 创建用于读写的电子表格

问题描述

我需要创建一个电子表格,如带有用户身份验证的谷歌表格。我一直坚持如何启动这个项目,因为我找不到需要使用哪个 NPM 模块。

所以请帮助任何人把我推向正确的方向?

标签: node.jsexcelnpmgoogle-sheets

解决方案


几周前我一直在做类似的任务。

所以这里是给你的迷你帮助。

1. 阅读并遵循Node.js 快速入门指南

密切关注下一个概念,例如:

  • 范围

例如,要从单元格中获取值,我们可以使用电子表格.values.get

此方法的范围是(使用其中的 1 个):

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets
https://www.googleapis.com/auth/spreadsheets.readonly

在 node.js 中它可以是一个数组

const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
  • 令牌

一旦你第一次运行你的index.js文件,终端会要求你授权,完成后你会token.json在你的工作目录中找到一个。

如果您更改 Scopes ->token.json从您的目录中删除

  • 电子表格 ID

当您创建/编辑电子表格时,您会得到类似的 url https://docs.google.com/spreadsheets/d/1eqRe0ksSwgOoPO0C_mZE6opjS1TlsCU5g1HtkiiILuw/edit#gid=0 1eqRe0ksSwgOoPO0C_mZE6opjS1TlsCU5g1HtkiiILuw是 ID


2. 使用Google Sheets API 参考创建自定义函数

示例如何获取单元格值

const sheets  = google.sheets({ version: 'v4', auth });
function getCellsValue(cells, callback){
  sheets.spreadsheets.values.get({
  spreadsheetId: 'spreadsheetId',
  range: cells
  }, (err, res) => {
    if (err) return console.log('Error #1001 : getCellsValue: ' + err);
    const output = res.data.values;
    if (output.length) {
      callback(output);
      return output;
    } else {
      console.log('No data found.');
    }
  });
}

// here is the example use of this function which output values from D2:D13
getCellsValue("D2:D13", (e) => {
  for(let i = 0; i < e.length; i++){
    console.log(e[i].toString());
  }
}, (err, res) => {
  if (err) return console.error('The API returned an error: ', err.message);
})

3. 使用 Try this API

这是非常有用的工具。

试试这个 API

如果您需要更多帮助,只需使用 Stackoverflow 以获得更高的透明度。当您提出非常详细的问题时,Stackoverflow 会为您提供帮助。

我希望这对您有所帮助,并且您可以开始您的 Google Sheets API 之旅。


推荐阅读