Znote (recipes)
  Get Znote  

Google Spreadsheet Integration

Interact with Google Spreadsheet using a service account and manage sheets programmatically

 

Google Spreadsheet Integration

Easily read, write, and manipulate Google Spreadsheets using a service account and the google-spreadsheet Node.js library.


🔗 Documentation


✅ Prerequisites

1. Enable the Google Sheets API

👉 Go to the Google Cloud Console 👈

  • Create or select a project
  • Navigate to APIs & Services > Library
  • Search for “Google Sheets API”
  • Click Enable

2. Create a Service Account

  • Go to APIs & Services > Credentials
  • Click + CREATE CREDENTIALS → choose Service account
  • Fill in the name/description → Click Create
  • Skip roles/permissions → Click Continue and then Done
  • Click on your service account → Go to Keys tab
  • Click + ADD KEY > Create new key → Select JSON → Download the file
  • Note the client_email field from the JSON

3. Share the Spreadsheet

  • Open your Google Spreadsheet
  • Click Share → Add the client_email from your JSON as an Editor

📦 Installation

Place your downloaded credentials file in the root of your project with this name: google-spreadsheet-credentials.json

open .

Install the required dependencies:

npm install google-spreadsheet@4.1.1 google-auth-library@9.6.3 --save

✏️ Example: Manipulate Spreadsheet

const { JWT } = require('google-auth-library');
const { GoogleSpreadsheet } = require('google-spreadsheet');
const creds = require('./google-spreadsheet-credentials.json');

const SCOPES = [
  'https://www.googleapis.com/auth/spreadsheets',
  'https://www.googleapis.com/auth/drive.file',
];

const jwt = new JWT({
  email: creds.client_email,
  key: creds.private_key,
  scopes: SCOPES,
});

// Replace with your actual Spreadsheet ID from the URL
const SPREADSHEET_ID = "YOUR_SPREADSHEET_ID";
const doc = new GoogleSpreadsheet(SPREADSHEET_ID, jwt);

await doc.loadInfo();
console.log(`Loaded spreadsheet: ${doc.title}`);

// Rename the document
await doc.updateProperties({ title: 'Renamed Spreadsheet' });

// Access the first sheet
const sheet = doc.sheetsByIndex[0];
console.log(`Working on sheet: ${sheet.title} (${sheet.rowCount} rows)`);

// Add a new sheet
const newSheet = await doc.addSheet({ title: 'My New Sheet' });
// To delete the new sheet:
// await newSheet.delete();

Related recipes