Skip to content

Instantly share code, notes, and snippets.

@nhancv

nhancv/gsheet.md Secret

Last active October 18, 2022 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhancv/5421c98ad774d849e3e049ec3ae913aa to your computer and use it in GitHub Desktop.
Save nhancv/5421c98ad774d849e3e049ec3ae913aa to your computer and use it in GitHub Desktop.
Google Sheets API:

Google Sheets API

Main steps:

yarn add dotenv googleapis@105
  • Update .env file
# Google Docs key path
# https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts
GSHEET_APIKEY_PATH=secrets/gkey.json
# https://docs.google.com/spreadsheets/d/[GSHEET_DOC_ID]/edit#gid=0
GSHEET_DOC_ID=xxx-xx
  • For example about reading and writing on the sheet
// node src/libs/gsheet.js
// Test connection: node -e "require('./src/libs/gsheet.js').connect()"

require('dotenv').config();
const { google } = require('googleapis');

const APIKEY_PATH = process.env.GSHEET_APIKEY_PATH;
const DOC_ID = process.env.GSHEET_DOC_ID;

let sheets;
const connect = async () => {
  if (!sheets) {
    try {
      const auth = new google.auth.GoogleAuth({
        keyFilename: APIKEY_PATH,
        scopes: ['https://www.googleapis.com/auth/spreadsheets'],
      });
      const authClient = await auth.getClient();
      sheets = google.sheets({ version: 'v4', auth: authClient });
    } catch (e) {
      console.log(`Google Cloud Connecting ERROR:`, e);
    }
  }
};

const readValue = async () => {
  try {
    await connect();
    const res = await sheets.spreadsheets.values.get({
      spreadsheetId: DOC_ID,
      range: ['Sheet1!A1:E'],
    });
    const rows = res.data.values;
    if (!rows || rows.length === 0) {
      console.log('No data found.');
      return;
    }
    console.log('Print columns A to E');
    rows.forEach((row) => {
      console.log(row);
    });
  } catch (e) {
    console.log(`Error readValue`, e);
  }
};

const writeValue = async () => {
  try {
    await connect();
    const res = await sheets.spreadsheets.values.append({
      spreadsheetId: DOC_ID,
      range: ['Sheet1!A1:E'],
      valueInputOption: 'USER_ENTERED',
      resource: {
        values: [[new Date()]],
      },
    });
    const rows = res.data.values;
    if (!rows || rows.length === 0) {
      console.log('No data found.');
      return;
    }
    console.log('Print columns A to E');
    rows.forEach((row) => {
      console.log(row);
    });
  } catch (e) {
    console.log(`Error writeValue`, e);
  }
};

module.exports = {
  connect,
  readValue,
  writeValue,
};
  • Test
# Read
node -e "require('./src/libs/gsheet.js').readValue()"
# Write
node -e "require('./src/libs/gsheet.js').writeValue()"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment