Saturday, February 11, 2017

Use Google apps script to make it interact with google spreadsheet

In previous posts (Hello World, Use variables in html page). In this post, we will learn how to use values written google spreadsheet in the web app made by google apps script.

1. Go to the spreadsheet and make a simple list on a sheet whose name is "sheet1" as follows.

A simple list like this:

IDList of fruits
1apple
2orange
3pineapple
4tangerine
5grape

2. Go to the script editor and write code in the html named as "index" as follows:


For your copy and paste:
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <?
      var sheetApp = SpreadsheetApp.getActiveSpreadsheet();
      //Or .openById("YOUR_SPREAD_SHEET_ID"); can be used too
      //spreadsheet ID can be found in URL of the spreadsheet:
      //https://docs.google.com/SPREAD SHEET ID/edit#gid=0
      var sheet    = sheetApp.getSheetByName("Sheet1");
      var data     = sheet.getRange(2,2).getValues();
    ?>
    <h1>I like <?= data  ?>. </h1>
  </body>
</html>
3. Save all and make a new version, then publish it. If you don't know how to make versions and publish them, please see previous posts (Hello World or Use variables in html page).

Maybe you will be asked this authorization after clicking "Update". Please authorize it.



4. Go to the URL which you published. You will see apple (that was cited from the spreadsheet) is written in the page.

The google apps script always refers to the spreadsheet, so if you change the value to "strawberry", the web app also shows "strawberry" instead of "apple".


Then reload the page... You can see "apple" is changed to "strawberry".


Of course you can use programming things such as for loop, so write codes between "<?" and "?>". For example, change the index as follows:


For your copy and paste:
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <?
      var sheetApp = SpreadsheetApp.getActiveSpreadsheet();
      //Or .openById("YOUR_SPREAD_SHEET_ID"); can be used too
      //spreadsheet ID can be found in URL of the spreadsheet:
      //https://docs.google.com/SPREAD SHEET ID/edit#gid=0
      var sheet = sheetApp.getSheetByName("Sheet1");
   
      for(var i=2;i<7;i++){
        var data = sheet.getRange(i,2).getValues();
        output.append('<h1>' + data + '</h1><br>');
      }
    ?>
  </body>
</html>
 Make a new version and publish it. The result is: