天天看点

google-spreadsheet:最流行的JS/TS Google Sheets技术!

作者:高级前端进阶

大家好,很高兴又见面了,我是"高级前端‬进阶‬",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力。

google-spreadsheet:最流行的JS/TS Google Sheets技术!

今天给大家带来的主题是 google-spreadsheet,即目前最流行的 JavaScript / TypeScript Google Sheets API 包装器。

前言

Excel 是电子表格代名词,在最初 Macintosh 上推出数十年后,Excel 仍然是最强大的电子表格应用程序,它已不再只是一个简单的桌面应用程序。 现在,开发者可以在 Windows、Mac、iOS、Android 甚至 Web 上使用 Excel,本文将围绕 google-spreadsheet 展开。

其实,在线表格是前端绕不开的永久话题,在日常开发中都或多或少的有类似的产品、技术述求。以前也单独发文介绍过不同的在线表格解决方案,如下面是已经发布文章的传送门:

  • 《 语雀弃用SpreadJs?在线表格Handsontable如何? 》
  • 《 语雀弃用SpreadJs?2023年前端表格 4+ 优秀热门方案! 》
  • 《 「续」语雀弃用SpreadJs?2023年前端表格4+热门方案! 》
  • 《 在线表格再添一员猛将excelize,支持 wasm!》

而本文将重点介绍 google-spreadsheet,话不多说,直接进入正题!

什么是 google-spreadsheet

Google Spreadsheets 是基于 Web 的应用程序,它允许使用者创建、更新和修改表格并在线实时分享数据。与基于 Ajax 的程序和微软的 Excel 和 CSV(逗号分隔值)文件兼容,表格也可以以 HTML 的格式保存。

借助 Google Spreadsheets ,开发者可以直接在浏览器中创建和编辑电子表格,无需任何特殊软件。支持多人同时工作、同步更改、自动保存。

google-spreadsheet:最流行的JS/TS Google Sheets技术!

总体来看,google-spreadsheet 是目前最流行的 JavaScript / TypeScript Google Sheets API 包装器。具有以下明显特征:

  • 多个身份验证选项(通过 google-auth-library): 服务帐户、OAuth、API 密钥、ADC 等,随时随地协作处理数据
  • 基于单元格的 API : 读取、写入、批量更新、格式化,智能填充和公式建议等辅助功能可更快地进行分析,并减少错误。只需使用简单语言针对数据提问,即可快速获得分析数据。
  • 基于行的 API : 读取、更新、删除(基于旧的 v3 基于行的调用)
  • 管理工作表 : 添加、删除、调整大小、更改标题、格式、复制、复制到其他工作表
  • 管理文档 : 创建新文档、删除文档、基本共享/权限,Google Sheets 可巧妙地连接到用户喜欢的其他 Google 应用,为您节省时间
  • 导出 : 下载各种格式的表格/文档

目前 google-spreadsheet 在 Github 上开源,有超过 2k 的 star、0.4k 的 fork、11.8k 的项目依赖量,代码贡献者 50+,是一个值得关注的优质前端开源项目。

使用 google-spreadsheet

下面例子从 google-spreadsheet 基础用法,处理表格行、单元格内容、管理文档和共享等多方面进行演示,更多示例、高级用法等可以继续参考文末的资料,里面有更多示例。

基础用法

import { GoogleSpreadsheet } from "google-spreadsheet";
import { JWT } from "google-auth-library";
// Initialize auth - see https://theoephraim.github.io/node-google-spreadsheet/#/guides/authentication
const serviceAccountAuth = new JWT({
  // 这里的环境变量值是从谷歌生成的服务帐户凭据复制的
  // 有关详细信息,请参阅文档中的“身份验证”部分
  email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
  key: process.env.GOOGLE_PRIVATE_KEY,
  scopes: ["https://www.googleapis.com/auth/spreadsheets"],
});

const doc = new GoogleSpreadsheet(
  "<the sheet ID from the url>",
  serviceAccountAuth
);

await doc.loadInfo();
// 加载文档属性和工作表
console.log(doc.title);
await doc.updateProperties({ title: "renamed doc" });

const sheet = doc.sheetsByIndex[0];
// 或使用 `doc.sheetsById[id]` 或 `doc.sheetsByTitle[title]`
console.log(sheet.title);
console.log(sheet.rowCount);

// 添加/删除工作表
const newSheet = await doc.addSheet({ title: "another sheet" });
await newSheet.delete();           

处理行

//如果创建新工作表,可以设置标题行
const sheet = await doc.addSheet({ headerValues: ['name', 'email'] });
// 添加 rows
const larryRow = await sheet.addRow({ name: 'Larry Page', email: '[email protected]' });
const moreRows = await sheet.addRows([
  { name: 'Sergey Brin', email: '[email protected]' },
  { name: 'Eric Schmidt', email: '[email protected]' },
]);

// 读取 rows,可以传入 { limit, offset }
const rows = await sheet.getRows();
// 读写行的值
console.log(rows[0].get('name'));
// 'Larry Page'
rows[1].set('email') = '[email protected]';
// 更新值
rows[2].assign({ name: 'Sundar Pichai', email: '[email protected]' });
//设置多个值
await rows[2].save();
// 保存行上的更改
await rows[2].delete();
 // 删除行           

Row 方法数据支持显式 TypeScript 类型。

type UsersRowData = {
  name: string;
  email: string;
  type?: 'admin' | 'user';
};
const userRows = await sheet.getRows<UsersRowData>();

userRows[0].get('name');
// <- TS is happy, knows it will be a string
userRows[0].get('badColumn');
// <- will throw a type error           

处理单元格

await sheet.loadCells("A1:E10");
// 将单元格范围加载到本地缓存中 - 不返回单元格
console.log(sheet.cellStats);
// 单元格总数,已加载,有多少个非空单元格
const a1 = sheet.getCell(0, 0);
//使用从零开始的索引访问单元格
const c6 = sheet.getCellByA1("C6");
// or A1 style notation
// access everything about the cell
console.log(a1.value);
console.log(a1.formula);
console.log(a1.formattedValue);
// 更新单元格内容和格式
a1.value = 123.456;
c6.formula = "=A1";
a1.textFormat = { bold: true };
c6.note = "This is a note!";
await sheet.saveUpdatedCells();
// 在一次调用中保存所有更新           

管理文档和共享

const auth = new JWT({
  email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
  key: process.env.GOOGLE_PRIVATE_KEY,
  scopes: [
    "https://www.googleapis.com/auth/spreadsheets",
    // 请注意,与共享相关的调用需要 google 云端硬盘scope
    "https://www.googleapis.com/auth/drive.file",
  ],
});

// 创建一个文档
const newDoc = await GoogleSpreadsheet.createNewSpreadsheetDocument(auth, {
  title: "new fancy doc",
});
// 与特定用户、域共享或公开
await newDoc.share("[email protected]");
await newDoc.share("mycorp.com");
await newDoc.setPublicAccessLevel("reader");

// 删除文档
await newDoc.delete();           

4.本文总结

本文主要和大家介绍 google-spreadsheet,即目前最流行的 JavaScript / TypeScript Google Sheets API 包装器。相信通过本文的阅读,大家对 google-spreadsheet 会有一个初步的了解。

因为篇幅有限,关于 google-spreadsheet 的更多用法和特性文章并没有过多展开,如果有兴趣,可以在我的主页继续阅读,同时文末的参考资料提供了大量优秀文档以供学习。最后,欢迎大家点赞、评论、转发、收藏,您的支持是我不断创作的动力。

参考资料

https://github.com/theoephraim/node-google-spreadsheet

https://www.google.com/sheets/about/

https://www.npmjs.com/package/google-auth-library

继续阅读