Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Last active October 23, 2023 09:00
Show Gist options
  • Save mhawksey/1276293 to your computer and use it in GitHub Desktop.
Save mhawksey/1276293 to your computer and use it in GitHub Desktop.
Google App Script to insert data to a google spreadsheet via POST or GET - updated version as per https://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
/*
Copyright 2011 Martin Hawksey
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Usage
// 1. Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
// 2. Run > setup
//
// 3. Publish > Deploy as web app
// - enter Project Version name and click 'Save New Version'
// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
// 4. Copy the 'Current web app URL' and post this in your form/script action
//
// 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(headRow, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
@ErNavi
Copy link

ErNavi commented Jul 24, 2017

Does it still works?

@kingslyroche
Copy link

working like charm...thank you so much,,,,my first google app is taking shape,...

@aravindr18
Copy link

Thank you for the amazing script. Did not work out of the box, but worked with some minor tweaks.

function doGet(e){
  return handleResponse(e);
}
 
function doPost(e){
  return handleResponse(e);
}
 
function handleResponse(e) {
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.
   
  try {
    // next set where we write the data - you could write to multiple/alternate destinations
     var ss = SpreadsheetApp.getActiveSpreadsheet();
     var sheet = ss.getSheets()[0];     
    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = []; 
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MMM d yyyy HH:mm:ss"));
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(e){
    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

@adrianoresende
Copy link

adrianoresende commented Oct 18, 2017

I get error "Failed to load https://script.google.com/macros/s/.../exec: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://bar.com' is therefore not allowed access. The response had HTTP status code 405."

How I fix this?

@dezostus
Copy link

dezostus commented Jan 5, 2018

@AravindK1992 thanks for the code! it works

@eli-oat
Copy link

eli-oat commented Jan 25, 2018

@AravindK1992, would you mind giving an example of how to define to what spreadsheet your code writes?

    // next set where we write the data - you could write to multiple/alternate destinations
     var ss = SpreadsheetApp.getActiveSpreadsheet();
     var sheet = ss.getSheets()[0];     

@followgeo
Copy link

Has anyone been able to modify this code to update a specific row on a spreadsheet?

@hamx0r
Copy link

hamx0r commented Feb 12, 2018

@followgeo The intent of this Gist is to add successive data to a sheet, as from an input form. The full Google Sheets API](https://developers.google.com/sheets/api/guides/values) is a good tool to use for updating a specific row.

@hamx0r
Copy link

hamx0r commented Feb 12, 2018

@mhawksey as @souprano noted, headRow is unused yet should be used as the 1st arg of the very next line:
var headers = sheet.getRange(headRow, 1, 1, sheet.getLastColumn()).getValues()[0];
I've made this change in my fork of your Gist.
https://gist.github.com/hamx0r/b851531d8546565c23deab926ee6867e

@shubhambhartiya I had the same problem because of 2 reasons:

  1. I had a typo in my client code for the header name (ie your sheet column is emaild but maybe your client is using a parameter email)
  2. I had more columns than I had fields in my HTTP request (ie I had 10 columns in my sheet, but only posted 7 key:value pairs, so 3 columns had undefined every time a new row was added)

@illtellyoulater
Copy link

Is there a way to fix the CORS error when doing a POST request?

@Prag1396
Copy link

how does this code work it does not even have the url for the spreadsheet to write to?

@rocobiz
Copy link

rocobiz commented Mar 16, 2018

How do you have someone that does not have a gmail account insert a record into the sheet when they complete form?

@shaungt1
Copy link

How could I use this to get All my data from Firebase? I have a database that has like 5 text fields, maps data, and a few images?? I would like to get this to a spreadsheet on Google sheets, I have tried other techniques that fail do to the limitations of the Data objects and Rows/Col

@neeksor
Copy link

neeksor commented Apr 6, 2018

Prag1396 - line 52
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));

https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app

@ownindra
Copy link

ownindra commented Aug 18, 2018

function doGet(e) {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1NMXd3bsq7pu2v3y3g6EdJ2g5yDmaRfOOpXAFGKZjn5E/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");

addUser(e,sheet);
}

function doPost(e) {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1NMXd3bsq7pu2v3y3g6EdJ2g5yDmaRfOOpXAFGKZjn5E/edit#gid=0");
var sheet = ss.getSheetByName("Sheet1");

addUser(e,sheet);
}

function addUser(e,sheet) {
var id = e.parameter.id ;
var name = e.parameter.name ;
var gender = e.parameter.gender ;
var kota = e.parameter.kota

sheet.appendRow([id,name,gender,kota]);
}

how to send data to the getRange spreadsheet ('C2'), in google script?

capture
1capture

@ownindra
Copy link

how to send data to the Range spreadsheet in ('C2'), in google script?

@AlexLPD
Copy link

AlexLPD commented Aug 23, 2019

Hi, Im tryng the code, is still runnign on 08 of 2019?
Mine says ok, buy wehen I try to upload some data, the browser send me; cant open site.

-Alex.

@jdwhite0722
Copy link

Hi, Is it possible to run a script like this from another script? I have two spreadsheets one that allows lots of users to search data from the master and edit specific fields only the other sheet is the master data sheet which is locked down so only a few can access and update direct. I have a button on the first sheet which i want to allow uses to submit their changes to the data. I currently get an error see attached file which i think is a result of the permissions. from what I can understand i should be able to create a script and publish as a web app then call that from my original button script setting the execution of that web app as executed by me getting round the permissions thing. Is this possible?

Screenshot 2019-09-24 at 09 51 43

@caracola
Copy link

Hello, I am using the Code to insert data throught webhooks but although I use lock, I lose events because of concurrence. Any idea how to solve It?

@ignacio-thfoot
Copy link

Great!! do you know how to grant script access to the users that share Edit access to the datasheet?
they can see the sheet and edit it, but no luck with the ajax thingy

@rajeev2834
Copy link

Which one is better doPost(e) or google.script.run.function(fn) to get value from users and submit it to spreadsheet?

@ewanjames
Copy link

Hi, looking to run very similar script.

Does anyone know if doPost could get round this problem;

  • I'm using Zapier, triggering Google sheets to create a new row is possible
  • However, In Google scripts, you can't use this event to trigger another event.

The only way I can currently do this is with having the data submitted in a Google Form + the 'On form submission' trigger.

Would doPost get round this?

@Roman-kazi
Copy link

Custom row number for Header

You didn't use the headRow variable anywhere.
To use custom header update the line 56 with var headers = sheet.getRange(headRow, 1, 1, sheet.getLastColumn()).getValues()[0];

@mhawksey
Copy link
Author

@Roman-kazi - thanks, updated :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment