Created
January 7, 2022 11:56
-
-
Save tomardern/3cfc0811c28c6ddbf7a72f23b6f39f7c to your computer and use it in GitHub Desktop.
Google Sheets API
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
function doPost(req) { | |
var jsonString = req.postData.getDataAsString(); | |
var data = JSON.parse(jsonString); | |
var sheetId = data.spreadsheetId; | |
var spreadsheet = SpreadsheetApp.openById(sheetId); | |
var sheet = spreadsheet.getSheets()[0]; | |
// Get the last row (The one we want to write into) | |
var rowIndex = sheet.getLastRow() + 1; | |
// If we have the range required, let's get the row we need to change | |
var idRange = 'MessageId'; | |
var messageId = data[idRange]; | |
if (messageId){ | |
messageId = messageId + ''; // Convert to string | |
var range = spreadsheet.getRangeByName(idRange); | |
var values = range.getValues(); | |
for(var i = 0; i < values.length; i++){ | |
if (values[i][0] && (values[i][0] + '') == messageId){ | |
rowIndex = i + 1; // Plus one due to row index | |
} | |
} | |
} | |
// Write each column (needs to match a "named range" in Google Sheets | |
for(var key in data){ | |
var range = spreadsheet.getRangeByName(key); | |
if (range != null) { | |
var columnIndex = range.getColumn(); | |
sheet.getRange(rowIndex, columnIndex).setValue(data[key]); | |
} | |
} | |
return ContentService.createTextOutput(JSON.stringify(data)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment