How can I select and copy a chart from a spreadsheet to a doc using Google Script?

偶尔善良 提交于 2020-03-26 22:34:06

问题


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:


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!



来源:https://stackoverflow.com/questions/31398583/how-can-i-select-and-copy-a-chart-from-a-spreadsheet-to-a-doc-using-google-scrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!