简体   繁体   中英

Inserting chart images from Spreadsheet into Document using GAS

My script which is contained in a Spreadsheet creates a new Document and inserts tables and paragraphs based on the Spreadsheet data. I also would like to insert charts (or jpg images of those charts) into the Document from the script. It seems to be possible, but does not work. This is my code:

function insertChartImage(){
  var charts = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Score Card').getCharts();
  var chart = charts[0].getAs('image/png');  // similar result with 'gif'
  var doc = DocumentApp.openById(documentId);
  doc.getBody().appendImage(chart);          // similar result with insertImage()
}

The result is a blank container result (and OF COURSE I'm signed in) saying "User not signed in".

I have sought far and wide for documentation, examples or tutorials but without any luck. Is this at all possible .... it seems like such a basic requirement... to be able to include charts in a document, but maybe that's just me?

I will really appreciate any advice or pointing me in the direction of good documentation.

The eventual solution was to rebuild the chart. Here is an example:

function insertBarChart(body) {   
  var values = SpreadsheetApp.getActive().getRange("Score!B2:D7").getValues();
  var dataTable = Charts.newDataTable()
        .addColumn(Charts.ColumnType.STRING, values[0][0])      
        .addColumn(Charts.ColumnType.NUMBER, values[0][1])      
        .addColumn(Charts.ColumnType.NUMBER, values[0][2])      
        .addRow(['Ownership', values[1][1], values[1][2]])   
        .addRow(['Control', values[2][1], values[2][2]])    
        .addRow(['Skills', values[3][1], values[3][2]])       
        .addRow(['Development', values[4][1], values[4][2]])   
        .addRow(['Social', values[5][1], values[5][2]])  
        .build(); 
  var chart = Charts.newColumnChart()      
    .setDataTable(dataTable)      
    .setColors(["green", "red"])      
    .setDimensions(600, 400)      
    .setXAxisTitle("Elements")      
    .setYAxisTitle("Points")      
    .setTitle("Profile")      
    .build();
  var scale = 0.5;
  var img = body.appendImage(chart.getAs('image/png'));
  img.setHeight(img.getHeight()*scale).setWidth(img.getWidth()*scale);
}

(May 2017) Google seems to have fixed this. Your original code works for me and does not yield blank containers:

function insertChartImage(){
  var charts = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Score Card').getCharts();
  var chart = charts[0].getAs('image/png');  // similar result with 'gif'
  var doc = DocumentApp.openById(documentId);
  doc.getBody().appendImage(chart);          // similar result with insertImage()
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM