如何根据从电子表格中提取的数据生成图表

时间:2019-06-13 03:18:23

标签: javascript google-apps-script charts google-sheets

我从电子表格中获得了一系列数据,这些数据将每周发送一次到电子邮件中。如何从数据生成图表?

我已经成功地从电子表格中提取了数据并将其发送到电子邮件中。我不确定如何使用提取的数据创建图表。

function CheckSales(){

  var app = SpreadsheetApp;
  var activeSheet = app.getActiveSpreadsheet().getSheets();
  //var data=activeSheet.getDataRange().getValues();

  //loop through sheets to look for value
  for (var i in activeSheet) {

  SpreadsheetApp.setActiveSheet(activeSheet[i])
  var sheet = app.getActiveSheet();
  var data = activeSheet[i].getDataRange().getValues();

  var emailAddress=SpreadsheetApp.getActiveSpreadsheet()
  .getSheetByName("Sheet1").getRange("B2").getValue();
  var resultArr=[];

  //To Loop through the whole data Rows
  for(var i=1;i<data.length;i++)
  {
    //Takes columns from L to S (To loop through the Columns)
    for(var j=11;j<19;j++)
    {
      var cellVal=data[i][j];
      Logger.log(cellVal)
      if(cellVal>0)
      {
        //Stores the Part No, Month Header Value of the Column, Cell Value 
which is greater then 0
        resultArr.push([data[i][0],data[0][j],cellVal])
      }
    }
  }
  if(resultArr.length>0)
  {
    var subject = 'Range exceeded Alert' + "" + sheet.getName();

    //Creates a body through the obtained values
    var body='';
    for(var m=0;m<resultArr.length;m++)
    {
      body+="For Part No "+resultArr[m][0].toString()+" and Month 
"+resultArr[m][1]
      .toString()+", Value is "+resultArr[m][2].toString()+"<br>";
    }

    MailApp.sendEmail({to:emailAddress,subject:subject,htmlBody:body});
  }

 }

}

现在我有两张包含数据的工作表,该数据将发送两次电子邮件,并提供零件号月份和值。我希望这些数据能够生成图表

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。下面是代码

  if (sheet.getCharts().length > 0){
  var chart = sheet.getCharts()[0];
  chart = chart.modify()
  .removeRange(chart.getRanges()[0])
  .addRange(sheet.getRange('L1:S22'))
  .build();
  sheet.updateChart(chart);
  }

  else{
  var sheet = SpreadsheetApp.getActiveSheet();
  var chart = sheet.newChart()
  .setPosition(5, 6, 5, 5)
  .setChartType(Charts.ChartType.BAR)
  .addRange(sheet.getRange('L1:S22'))
  .build();
  sheet.insertChart(chart);
  }
  var charts = SpreadsheetApp.getActiveSheet().getCharts();



 MailApp.sendEmail({to:emailAddress,subject:subject,htmlBody:body,attachments: 
 charts});