Google Sheets + GAppsScript = Database

GAppsScript is a scripting platform for light-weight application development in the Google Workspace platform. Because it is free and runs on Google platform, it is a great choice for those who want to setup a simple database without money. To achieve this, we need to attach a new script to our Google Sheet.Click “Tools -> Script Editor” on the top tool bar. Then creat a function to handle post requests:

1
2
3
function doPost(e)  {
//Do something
}

We can get our sheet by this:
1
2
let SpreadSheet = SpreadsheetApp.openById("<Sheet ID>");
let Sheet = SpreadSheet.getSheets()[0];//Get first sheet

The Sheet ID can be found in sheet’s url:
1
https://docs.google.com/spreadsheets/d/<Sheet ID>/edit#gid=0

There are some useful APIs to interact with the sheet:
1
2
Sheet.getLastRow();//Get the index of the last row having value
Sheet.getRange(12).setValue("123");//set the value of (row, column)

To be more specific, here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function doPost(e{
  // Get data
  let params = e.parameter; 
  let name = params.name;
  let mail = params.mail;
 
  let SpreadSheet = SpreadsheetApp.openById("ID");
  let Sheet = SpreadSheet.getSheets()[0]; 
  let LastRow = Sheet.getLastRow();

  // Write data
  Sheet.getRange(LastRow+11).setValue(name);
  Sheet.getRange(LastRow+12).setValue(mail);
  
  // Return
  return ContentService
  .createTextOutput(JSON.stringify({ result'Success'version'1.0' }))
      .setMimeType(ContentService.MimeType.JSON); 
}

After editing done, click “Deploy->New Deployment.”
1
2
3
4
Deploy type: WebApp
Configuration:
Execute as: Me
Who has access: Anyone

And you can send a post request to the given link to test it.


本Blog所有文章除特別聲明外,均採用 CC BY-SA 4.0 協定 ,轉載請註明出處