Google Sheets API Client

5.2.0 · active · verified Tue Apr 21

The `google-spreadsheet` package provides a robust and easy-to-use JavaScript/TypeScript interface for interacting with the Google Sheets API. It simplifies common tasks like reading, writing, and manipulating data within spreadsheets, as well as managing sheets and documents themselves. The current stable version is `5.2.0`, and the project maintains an active development cycle with frequent minor and patch updates for new features, bug fixes, and dependency synchronization. Key differentiators include comprehensive support for multiple authentication methods via `google-auth-library` (service account, OAuth 2.0, API key, ADC), both cell-based and row-based APIs for flexible data interaction, extensive methods for managing worksheets and documents (e.g., adding, removing, resizing, updating properties, setting permissions), and built-in automatic retries with exponential backoff for API requests, enhancing reliability against transient network issues and rate limits. It aims to be the most popular wrapper, abstracting away the complexities of the underlying Google Sheets API.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing the GoogleSpreadsheet client with service account credentials, loading document properties, and performing basic operations like reading/updating document/sheet titles and managing sheets.

import { GoogleSpreadsheet } from 'google-spreadsheet';
import { JWT } from 'google-auth-library';

// Initialize auth - use environment variables for security
// process.env.GOOGLE_PRIVATE_KEY should have '\n' replaced with '\\n' if set as env var
const serviceAccountAuth = new JWT({
  email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL ?? '',
  key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n') ?? '', // Handle escaped newlines
  scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});

async function main() {
  const doc = new GoogleSpreadsheet(process.env.GOOGLE_SHEET_ID ?? '', serviceAccountAuth);

  await doc.loadInfo(); // loads document properties and worksheets
  console.log('Document title:', doc.title);
  await doc.updateProperties({ title: 'Renamed Doc via API' });
  console.log('Updated document title to:', doc.title);

  const sheet = doc.sheetsByIndex[0]; // Access the first sheet
  console.log('First sheet title:', sheet.title);
  console.log('First sheet row count:', sheet.rowCount);

  // Adding and removing a new sheet
  const newSheet = await doc.addSheet({ title: 'Another Sheet ' + Date.now() });
  console.log('Added new sheet:', newSheet.title);
  await newSheet.delete();
  console.log('Deleted the new sheet.');
}

// Run the main function (or wrap in an IIFE if top-level await is not supported)
main().catch(console.error);

view raw JSON →