Created
June 8, 2021 02:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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