Skip to content

Instantly share code, notes, and snippets.

@grant
Last active August 1, 2020 02:45
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 grant/98aacdb24e9e0fc0ff5b6d8987ef4e12 to your computer and use it in GitHub Desktop.
Save grant/98aacdb24e9e0fc0ff5b6d8987ef4e12 to your computer and use it in GitHub Desktop.
Sheets as a Service – Basic Script
const path = require('path');
const {google} = require('googleapis');
const sheets = google.sheets('v4');
// TODO: Add your Sheet ID
// https://docs.google.com/spreadsheets/d/2L2LpYPyxJQTf14OLM6mVuiou88MsEi4Q-IUUxswNlfe/edit
const SPREADSHEET_ID = '2L2LpYPyxJQTf14OLM6mVuiou88MsEi4Q-IUUxswNlfe';
/**
* Appends row data to the Google Sheet
*/
const appendToSheet = async (row) => {
// Obtain user credentials to use for the request
const auth = new google.auth.GoogleAuth({
keyFile: path.join(__dirname, 'creds.json'),
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
google.options({auth});
await sheets.spreadsheets.values.append({
spreadsheetId: SPREADSHEET_ID,
range: 'A1:A1', // Needed, but not used when values are present.
valueInputOption: 'USER_ENTERED',
requestBody: {
values: [
row, // Example: ['Grant', '1/1/2000'],
],
},
});
}
/**
* Simple Express server (via Functions Framework) with an Express request/response.
*/
exports.addRow = (req, res) => {
const row = [
'ADDED_ROW', new Date(),
];
appendToSheet(row);
res.send(`Added row: ${row}`);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment