Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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. Run the setup function (you'll need to do this twice - 1st time to grant acces to Script Properties)
2. Share > Publish as service ... set security level and enable service
3. Copy the service URL and post this in your form/script action
4. Insert column names on the DATA sheet matching the parameter names of the data you are passing
*/
function doGet(e) { // change to doPost(e) if you are recieving POST data
var ss = SpreadsheetApp.openById(ScriptProperties.getProperty('active'));
var sheet = ss.getSheetByName("DATA");
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; //read headers
var nextRow = sheet.getLastRow(); // get next row
var cell = sheet.getRange('a1');
var col = 0;
for (i in headers){ // loop through the headers and if a parameter name matches the header name insert the value
if (headers[i] == "Timestamp"){
val = new Date();
} else {
val = e.parameter[headers[i]];
}
cell.offset(nextRow, col).setValue(val);
col++;
}
//http://www.google.com/support/forum/p/apps-script/thread?tid=04d9d3d4922b8bfb&hl=en
var app = UiApp.createApplication(); // included this part for debugging so you can see what data is coming in
var panel = app.createVerticalPanel();
for( p in e.parameters){
panel.add(app.createLabel(p +" "+e.parameters[p]));
}
app.add(panel);
return app;
}
//http://www.google.sc/support/forum/p/apps-script/thread?tid=345591f349a25cb4&hl=en
function setUp() {
ScriptProperties.setProperty('active', SpreadsheetApp.getActiveSpreadsheet().getId());
}
@imnotberg
Copy link

imnotberg commented Jul 28, 2016

When you say in line 4 under usage- "post this in your form/script action"

Do we need to create a new form from the spreadsheet and alter the url?

Please clarify- thanks for the code.

@myexpertiseforyou
Copy link

myexpertiseforyou commented Aug 2, 2016

Hey Can i write google calendar API interaction in app script? Or how i can send my data from client JavaScript file. I want to auto update a spreadsheet with fetching data from google calendar and want to update row of spreadsheet.

Thanks in advance

@AishwaryT
Copy link

AishwaryT commented Oct 20, 2016

Hey, i have made a file for insert, update, delete and retrive, with similar code. Please check https://github.com/AishwaryT/Google-app-script-crud

@dassram17
Copy link

dassram17 commented Jan 5, 2017

i just want to check post request, as per the request i want to save my datas in sheet1 or sheet2 how to alter the sheet names from above script..

@karan-ta
Copy link

karan-ta commented Apr 13, 2017

@dassram17 i have not tried your requirement.
but you can try to send the sheetname as a parameter of your form.
then access it as e.parameter.sheet_name

good luck.

@karan-ta
Copy link

karan-ta commented Apr 13, 2017

@imnotberg
no.
just write the form tag in your own html.
in the action - write the url of the webapp from => Publish -> Deploy as a web app
example -

action is your webapp url.
cheers.

@ErNavi
Copy link

ErNavi commented Jul 24, 2017

Does it still works?

@kingslyroche
Copy link

kingslyroche commented Oct 2, 2017

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

@aravindr18
Copy link

aravindr18 commented Oct 7, 2017

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

followgeo commented Feb 1, 2018

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

illtellyoulater commented Feb 15, 2018

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

@Prag1396
Copy link

Prag1396 commented Feb 18, 2018

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

shaungt1 commented Mar 23, 2018

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

ownindra commented Aug 18, 2018

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

jdwhite0722 commented Sep 24, 2019

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

caracola commented Jun 18, 2020

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

ignacio-thfoot commented Oct 6, 2020

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

rajeev2834 commented Jan 15, 2021

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

ewanjames commented Apr 8, 2021

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

Roman-kazi commented May 24, 2021

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

mhawksey commented May 24, 2021

@Roman-kazi - thanks, updated :)

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