How can I select and copy a chart from a spreadshe

2019-09-17 11:49发布

For example, I have a google spreadsheet which contain a chart, is there any way to copy this chart to a google doc (as an image) using google script?

1条回答
一纸荒年 Trace。
2楼-- · 2019-09-17 12:10

Here is the code to copy a chart from Google Spreadsheet to a document:

function sheetChart()
{
  try
  {
    var sheet = DocumentApp.getActiveDocument().getBody().appendImage(myChart());
  }
  catch(err)
  {
    Logger.log(err);
  }
}


function myChart()
{
    try
    {
      var data = Charts.newDataTable()
      .addColumn(Charts.ColumnType.NUMBER, 'Month')
      .addColumn(Charts.ColumnType.NUMBER, 'In Store');

      var sheet = SpreadsheetApp.openById('Spreadsheet ID').getActiveSheet().getRange(2,1,4,2).getValues();

      for(var i =0;i< sheet.length;i++)data.addRow(sheet[i]);
      data.build();

      var chart = Charts.newColumnChart()
                  .setDataTable(data)
                  .setStacked()
                  .setRange(0, 40)
                  .setTitle('Sales per Month')
                  .build();
     }catch(err){
            Logger.log(err);
      }
      return chart.getBlob();
}

Data added in the sheet is:

profitability   sales
11.00   10000
12.00   11000
13.00   12000
14.00   13000

Added this code in document script editor and it is copying the chart as image in the doc.

Hope that helps!

查看更多
登录 后发表回答