Search code examples
google-apps-scriptgoogle-sheets-api

GAS Column Chart from spreadsheet data


On this link, a chart is prepared in GAS with hard-coded data and they have mentioned that you can get data from SpreadsheetApp.

Please can someone assist me - how to build datatable (columns, rows) in GAS Charts from spreadsheet.

I tried the following but was unsuccessful

var ss = SpreadsheetApp.openById("myid");
var datatable = ss.getSheetByName("Chart sheet").getRange("A1:H4").getValues();

var chart = Charts.newColumnChart()      
  .setDataTable(dataTable)      
  .setRange(0, 40)
  .setTitle('Chart')
  .setLegendPosition(Charts.Position.BOTTOM)
  .setDimensions(600, 300)
  .build();

I have used the code as doGet function, the output returns the following error:-

Cannot call overloaded constructor setDataTable with parameters (object) because there is more than one matching constructor signature: interface (class) setDataTable(DataTableBuilder) interface (class) setDataTable(DataTableSource)

Solution

  • You are using getValues() after getting the range (Line 2). To fix it just remove getValues(). You also have a typo in setDataTable(dataTable) the variable you declared is in lowercase: datatable*

    See the code fixed bellow:

    var ss = SpreadsheetApp.openById("myid");
    var datatable = ss.getSheetByName("Chart sheet").getRange("A1:H4");
    
    var chart = Charts.newColumnChart()      
      .setDataTable(datatable)      
      .setRange(0, 40)
      .setTitle('Chart')
      .setLegendPosition(Charts.Position.BOTTOM)
      .setDimensions(600, 300)
      .build();
    

    The API can be found here.

    * Credit to @kbrizy for noting the variable typo.