node.js - 使用 Node js 创建用于读写的电子表格
问题描述
我需要创建一个电子表格,如带有用户身份验证的谷歌表格。我一直坚持如何启动这个项目,因为我找不到需要使用哪个 NPM 模块。
所以请帮助任何人把我推向正确的方向?
解决方案
几周前我一直在做类似的任务。
所以这里是给你的迷你帮助。
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
这是非常有用的工具。
如果您需要更多帮助,只需使用 Stackoverflow 以获得更高的透明度。当您提出非常详细的问题时,Stackoverflow 会为您提供帮助。
我希望这对您有所帮助,并且您可以开始您的 Google Sheets API 之旅。
推荐阅读
- php - 如何在 PHP 中的函数之外获取函数名称?
- python - 如何在 Python 中为我的 CSV 文件将 UTC 转换为 CEST
- cmake - 什么是“NOCONFIG”值?
- java - 无法使用 java 客户端 7.0 滚动带有 appium 的 android 本机应用程序
- javascript - 验证 render() 中使用的状态中的变量以设置样式/填充 html
- sql - 将 RAW SQL 作为参数传递给函数以检查数据是否存在的问题
- python-3.x - Azure 数据工厂 - 数据集
- javascript - 如何使用 TypeError 解决此问题
- c# - 在 c# vscode 中缺少使用指令程序集引用错误
- groovy - 在 groovy 中动态更新键值对