The most popular Google Sheets API wrapper for javascript / typescript
- 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
(ornpm i google-spreadsheet --saveoryarn add google-spreadsheet)
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:
(asyncfunction(){awaitsomeAsyncFunction();})();import{GoogleSpreadsheet}from'google-spreadsheet';import{JWT}from'google-auth-library';// Initialize auth - see https://theoephraim.github.io/node-google-spreadsheet/#/guides/authenticationconstserviceAccountAuth=newJWT({// env var values here are copied from service account credentials generated by google// see "Authentication" section in docs for more infoemail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,key: process.env.GOOGLE_PRIVATE_KEY,scopes: ['https://www.googleapis.com/auth/spreadsheets'],});constdoc=newGoogleSpreadsheet('<the sheet ID from the url>',serviceAccountAuth);awaitdoc.loadInfo();// loads document properties and worksheetsconsole.log(doc.title);awaitdoc.updateProperties({title: 'renamed doc'});constsheet=doc.sheetsByIndex[0];// or use `doc.sheetsById[id]` or `doc.sheetsByTitle[title]`console.log(sheet.title);console.log(sheet.rowCount);// adding / removing sheetsconstnewSheet=awaitdoc.addSheet({title: 'another sheet'});awaitnewSheet.delete();More info:
// if creating a new sheet, you can set the header rowconstsheet=awaitdoc.addSheet({headerValues: ['name','email']});// append rowsconstlarryRow=awaitsheet.addRow({name: 'Larry Page',email: 'larry@google.com'});constmoreRows=awaitsheet.addRows([{name: 'Sergey Brin',email: 'sergey@google.com'},{name: 'Eric Schmidt',email: 'eric@google.com'},]);// read rowsconstrows=awaitsheet.getRows();// can pass in { limit, offset }// read/write row valuesconsole.log(rows[0].get('name'));// 'Larry Page'rows[1].set('email','sergey@abc.xyz');// update a valuerows[2].assign({name: 'Sundar Pichai',email: 'sundar@google.com'});// set multiple valuesawaitrows[2].save();// save updates on a rowawaitrows[2].delete();// delete a rowRow methods support explicit TypeScript types for shape of the data
typeUsersRowData={name: string;email: string;type?: 'admin'|'user';};constuserRows=awaitsheet.getRows<UsersRowData>();userRows[0].get('name');// <- TS is happy, knows it will be a stringuserRows[0].get('badColumn');// <- will throw a type errorMore info:
awaitsheet.loadCells('A1:E10');// loads range of cells into local cache - DOES NOT RETURN THE CELLSconsole.log(sheet.cellStats);// total cells, loaded, how many non-emptyconsta1=sheet.getCell(0,0);// access cells using a zero-based indexconstc6=sheet.getCellByA1('C6');// or A1 style notation// access everything about the cellconsole.log(a1.value);console.log(a1.formula);console.log(a1.formattedValue);// update the cell contents and formattinga1.value=123.456;c6.formula='=A1';a1.textFormat={bold: true};c6.note='This is a note!';awaitsheet.saveUpdatedCells();// save all updates in one callMore info:
constauth=newJWT({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 docconstnewDoc=awaitGoogleSpreadsheet.createNewSpreadsheetDocument(auth,{title: 'new fancy doc'});// share with specific users, domains, or make publicawaitnewDoc.share('someone.else@example.com');awaitnewDoc.share('mycorp.com');awaitnewDoc.setPublicAccessLevel('reader');// delete docawaitnewDoc.delete();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.
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
None yet - get in touch!
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.
This is free and unencumbered public domain software. For more info, see https://unlicense.org.