Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var SHEET_NAME = "Sheet1"; // Enter sheet name where data is to be written
var inputFields = ["nombre", "email", "comentarios"];
var SCRIPT_PROP = PropertiesService.getScriptProperties();
function doRequest(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var lastColumn = sheet.getLastColumn();
if(lastColumn==0){
sheet.getRange(1, 1, 1,inputFields.length).setValues([inputFields]);
}
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; //getRange(row, column, numRows, numColumns)
var nextRow = sheet.getLastRow()+1;
var row = [];
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else {
if(headers[i]){
row.push(e.parameter[headers[i]]);
}
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
return HtmlService.createHtmlOutput(JSON.stringify({"result":"success", "data": e}));
} catch(e){
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally {
lock.releaseLock();
}
}
function doPost(e){return doRequest(e);}
function doGet(e){return doRequest(e);}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
function testSheetsWrite() {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var lastColumn = sheet.getLastColumn();
if(lastColumn==0){
sheet.getRange(1, 1, 1,inputFields.length).setValues([inputFields]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment