Search code examples
javascriptgoogle-apps-scriptdatatablegoogle-visualizationgoogle-apps

Returning a serverside datatable to client with google App Script


I want to return a datatable I created in google apps script with data from a Spreadsheet to the client. I use a succesHandler to get the data and use this to create a chart. The only problem i have is that my data is null. It seems i can't return a datatable object to the client page.

I need to send it to the client, because Google Apps script is deprecating the UIApp functions so i need the google.visualization functions in the Client.

Code.gs

function doGet() {  return HtmlService.createHtmlOutputFromFile('Index.html')
  .setSandboxMode(HtmlService.SandboxMode.IFRAME);}

function getDataTable()
{
  var bestanden = DriveApp.searchFiles('title contains "' + "kwalrap" + '"');
  while (bestanden.hasNext()) 
  {
    var bestand = bestanden.next();
    var docid = ( bestand.getId() );
       Logger.log(docid);
    };
  var sheets= SpreadsheetApp.openById(docid).getSheets();
  //vanaf sheet 0. tot hij bij de laatset sheet is. dan steeds 2 sheets verder.
  for(var j = 0; j < 2; j = j+1)
  {
    var sheet = sheets[j];
    //Logger.log(sheet.getSheetName());
    var range = sheet.getRange(2,1,sheet.getLastRow(),8);
    var inforange = sheet.getRange(2,1,1,8);
    var values = range.getValues();
    var infovalues = inforange.getValues();
    var data = Charts.newDataTable()
      .addColumn(Charts.ColumnType.STRING, "Tijd")
      .addColumn(Charts.ColumnType.NUMBER, "dco")
      .addColumn(Charts.ColumnType.NUMBER, "dcp")
      .addColumn(Charts.ColumnType.NUMBER, "dct")
      .addColumn(Charts.ColumnType.NUMBER, "dcz")
      .addColumn(Charts.ColumnType.NUMBER, "ldc")
      .addColumn(Charts.ColumnType.NUMBER, "lv")      

    for(var i = 0; i < sheet.getLastRow()-1; i++)
    {
      data.addRow([values[i][0],values[i][1],values[i][2],values[i][3],values[i][4],values[i][5],values[i][6]]);
      Logger.log(values[i]);
    }
   var dataTable = data.build();
   return dataTable;
// return  JSON.stringify(values);
  }
}

Index.html

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript">

   google.load("visualization", "1", {packages:["corechart"]});

    function onSuccess(data) {
  var options = {
      title: 'Why doesn't this work'
    };
  new google.visualization.LineChart(
      document.getElementById('visualization_div')).draw(data, options);
  }

  google.script.run.withSuccessHandler(onSuccess)
      .getDataTable();

 </script>
    </head>
 <body>
    <div id="visualization_div" style="width: 600px; height: 380px;';"></div>
     </body>
</html>

why is my data variable null in the onSuccesHandler and how do i get the datatable in the client

Thanks for your help


Solution

  • Its because you need to return a plain javascript array, not a data table which is purely a server-side object.