Interact with Google Spreadsheet using a service account and manage sheets programmatically
Easily read, write, and manipulate Google Spreadsheets using a service account and the google-spreadsheet
Node.js library.
👉 Go to the Google Cloud Console 👈
client_email
field from the JSONclient_email
from your JSON as an EditorPlace 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
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();