@budibase/google-spreadsheet

中文文档
4.1.5发布于 2024/09/19UnlicenseTypeScriptESM + CJS近 30 天下载 3.8万

Google Sheets API -- simple interface to read/write data and manage sheets

原始使用文档
文档目录10 节
  1. Examples
  2. The Basics
  3. Working with rows
  4. Working with cells
  5. Managing docs and sharing
  6. Why?
  7. Support & Contributions
  8. Sponsors
  9. Contributing
  10. License

google-spreadsheet

The most popular Google Sheets API wrapper for javascript / typescript

NPM version CI status Known Vulnerabilities NPM

  • multiple auth options (via google-auth-library) - service account, OAuth, API key, ADC, etc
  • cell-based API - read, write, bulk-updates, formatting
  • row-based API - read, update, delete (based on the old v3 row-based calls)
  • managing worksheets - add, remove, resize, update properties (ex: title), duplicate to same or other document
  • managing docs - create new doc, delete doc, basic sharing/permissions
  • export - download sheet/docs in various formats

Docs site - Full docs available at https://theoephraim.github.io/node-google-spreadsheet


🌈 Installation - pnpm i google-spreadsheet
(or npm i google-spreadsheet --save or yarn add google-spreadsheet)

Examples

The following examples are meant to give you an idea of just some of the things you can do

IMPORTANT NOTE - To keep the examples concise, I'm calling await at the top level which is not allowed in some older versions of node. If you need to call await in a script at the root level and your environment does not support it, you must instead wrap it in an async function like so:

(async function () {
  await someAsyncFunction();
})();

The Basics

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({
  // env var values here are copied from service account credentials generated by google
  // see "Authentication" section in docs for more info
  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(); // loads document properties and worksheets
console.log(doc.title);
await doc.updateProperties({ title: 'renamed doc' });

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

// adding / removing sheets
const newSheet = await doc.addSheet({ title: 'another sheet' });
await newSheet.delete();

More info:

Working with rows

// if creating a new sheet, you can set the header row
const sheet = await doc.addSheet({ headerValues: ['name', 'email'] });

// append 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]' },
]);

// read rows
const rows = await sheet.getRows(); // can pass in { limit, offset }

// read/write row values
console.log(rows[0].get('name')); // 'Larry Page'
rows[1].set('email', '[email protected]'); // update a value
rows[2].assign({ name: 'Sundar Pichai', email: '[email protected]' }); // set multiple values
await rows[2].save(); // save updates on a row
await rows[2].delete(); // delete a row

Row methods support explicit TypeScript types for shape of the data

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

More info:

Working with cells

await sheet.loadCells('A1:E10'); // loads range of cells into local cache - DOES NOT RETURN THE CELLS
console.log(sheet.cellStats); // total cells, loaded, how many non-empty
const a1 = sheet.getCell(0, 0); // access cells using a zero-based index
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);
// update the cell contents and formatting
a1.value = 123.456;
c6.formula = '=A1';
a1.textFormat = { bold: true };
c6.note = 'This is a note!';
await sheet.saveUpdatedCells(); // save all updates in one call

More info:

Managing docs and sharing

const auth = new JWT({
  email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
  key: process.env.GOOGLE_PRIVATE_KEY,
  scopes: [
    'https://www.googleapis.com/auth/spreadsheets',
    // note that sharing-related calls require the google drive scope
    'https://www.googleapis.com/auth/drive.file',
  ],
});

// create a new doc
const newDoc = await GoogleSpreadsheet.createNewSpreadsheetDocument(auth, { title: 'new fancy doc' });

// share with specific users, domains, or make public
await newDoc.share('[email protected]');
await newDoc.share('mycorp.com');
await newDoc.setPublicAccessLevel('reader');

// delete doc
await newDoc.delete();

Why?

This module provides an intuitive wrapper around Google's API to simplify common interactions

While Google's v4 sheets API is much easier to use than v3 was, the official googleapis npm module is a giant autogenerated meta-tool that handles every Google product. The module and the API itself are awkward and the docs are pretty terrible, at least to get started.

In what situation should you use Google's API directly?
This module makes trade-offs for simplicity of the interface. Google's API provides a mechanism to make many requests in parallel, so if speed and efficiency are extremely important to your use case, you may want to use their API directly. There are also many lesser-used features of their API that are not implemented here yet.

Support & Contributions

This module was written and is actively maintained by Theo Ephraim.

Are you actively using this module for a commercial project? Want to help support it?
Buy Theo a beer

Sponsors

None yet - get in touch!

Contributing

Contributions are welcome, but please follow the existing conventions, use the linter, add relevant tests, and add relevant documentation.

The docs site is generated using docsify. To preview and run locally so you can make edits, run npm run docs:preview and head to http://localhost:3000 The content lives in markdown files in the docs folder.

License

This is free and unencumbered public domain software. For more info, see https://unlicense.org.

版本与发布记录

@budibase/google-spreadsheet 共发布 4 个版本,首次发布于 2024/05/17;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.1.5latest2024/09/192 年前
4.1.42024/09/192 年前
4.1.32024/08/052 年前
4.1.22024/05/172 年前

关于 @budibase/google-spreadsheet 的常见问题

@budibase/google-spreadsheet 是什么?

Google Sheets API -- simple interface to read/write data and manage sheets

如何安装 @budibase/google-spreadsheet?

在项目目录运行 npm install @budibase/google-spreadsheet,或使用 pnpm add / yarn add / bun add。

@budibase/google-spreadsheet 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@budibase/google-spreadsheet 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@budibase/google-spreadsheet 可以商用吗?

@budibase/google-spreadsheet 使用 Unlicense 许可。作者将代码贡献到公共领域,可不受限制地使用。以上为概括,不构成法律意见,请以许可原文为准。

@budibase/google-spreadsheet 的下载量有多少?

根据 npm 官方下载统计,@budibase/google-spreadsheet 在 2026/10/09 – 2026/11/07 这 30 天内被下载 37,732 次,日均约 1,258 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@budibase/google-spreadsheet 还在维护吗?

最新版本 4.1.5 发布于 2024/09/19(2 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/05/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。