Skip to content

Instantly share code, notes, and snippets.

@markelliot
Created June 8, 2021 02:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markelliot/b4454cd49280a4c0ae0b2126b9e31d27 to your computer and use it in GitHub Desktop.
Save markelliot/b4454cd49280a4c0ae0b2126b9e31d27 to your computer and use it in GitHub Desktop.
Appends rows to a Google Sheet using the specified OAuth2 token and spreadsheet id.
/**
* Appends the row matrix to the specified range in the identified sheet.
*
* @param {string} token an OAuth2 token scoped for write to the Google sheets APIs
* (scope must include "https://www.googleapis.com/auth/spreadsheets") and with access
* to the underlying Google Sheet. The Sheet should be shared with the service user's
* email address.
* @param {string} spreadsheetId the spreadsheet's identifier, which you can glean
* from the Google Sheets URL, extracted from the pattern:
* https://docs.google.com/spreadsheets/d/([A-Za-z0-9_-]+)/edit#gid=0
* @param {string} range the range to append to, for the home row this is "A1:A1"
* @param {string[][]} rows the rows to append, must be an array of an array of strings
* @returns the Google API result object
*/
async function appendRowsToSheet(token, spreadsheetId, range, rows) {
try {
return await fetch(
`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${range}:append?valueInputOption=USER_ENTERED`,
{
"method": "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
body: JSON.stringify({
"range": range,
"majorDimension": "rows",
"values": rows
})
})
} catch (err) {
console.log(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment