In google sheets I have a tab with a button that calls a script that do some stuff and generates a chart. I would like to add to the end of the script a code that generates and download an image of the generated chart.
In top right of the chart there is an option that does that, so I recorded a macro doing this but nothing was generated.
Couldn't find a way to do that. Any clue?
Thank You
This will put a png image into a Google Doc:
function chartImage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet()
var chart = sheet.newChart()
.setChartType(Charts.ChartType.BAR)
.addRange(sheet.getDataRange())
.setPosition(5, 5, 0, 0)
.setOption("title", "Dynamic Chart")
.build();
sheet.insertChart(chart);
var img=sheet.getCharts()[0].getBlob().getAs('image/png');
var doc=DocumentApp.openById('Doc Id');
doc.getBody().appendImage(img);
}
This code will get the image saved in your Drive and put the URL in one of your cells in your spreadsheet:
function downloadChart() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("Range where the chart is located");
// Get chart and save it into your Drive
var chart = sheet.getCharts()[0];
var file = DriveApp.createFile(chart.getBlob());
// Set url in one cell and resize the column
sheet.getRange(23, 1).setValue(file.getUrl())
sheet.autoResizeColumn(1);
}
As a workaround for a direct download when you click the button, I recommend you to check this post.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.