The goal here to programmatically create a chart from a pre-existing data, when a Spreadsheet has loaded.
The documentation for the EmbeddedChart class has two examples, both modifying existing charts, and, as I require, creating a new one:
function newChart(range, sheet){
var sheet = SpreadsheetApp.getActiveSheet();
var chartBuilder = sheet.newChart();
chartBuilder.addRange(range)
.setChartType(Charts.ChartType.Line)
.setOption('title', 'My Line Chart!');
sheet.insertChart(chartBuilder.build());
}
Google example is missing: .setPosition()
I've tried implementing this function, as so:
function makeChart(sheet, range) {
Logger.log('MAKING CHART');
var chart = sheet.newChart();
chart.addRange(range)
.setChartType(Charts.ChartType.BAR)
.setOption('title','I love Google Apps Script');
sheet.insertChart(chart.build());
}
Where sheet and range are defined as:
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("C1:D16");
makeChart()
is called from onOpen()
, which I can see is being executed. Despite this, the chart never appears in the spreadsheet.
I've noticed nothing will be logged after the .build()
method has been called, but there's little in the docs about this method, beyond stating that it must be called after making a chart.
Edit: The script fails because .insertChart()
expects an EmbeddedChart
object, but is given an EmbeddedChartBuilder
. The .build()
method, according to the docs, should return an EmbeddedChart. But it doesn't.