Emailing a chart from a Google spreadsheet with apps script

对着背影说爱祢 提交于 2019-12-05 01:16:54

问题


I've search high and low for an answer but without an y luck. Got a Google spreadsheet which uses apps script to connect to a database to pull in some raw data into a spreadsheet. I then use various spreadsheet formulas to manipulate that data and then final create a chart.

My next challenge is that I want to be able to embed that chart into an email via apps script and send it as an HTML email..

Is this at all possible or should I start looking for some other solution?

Thanks!

Mikael


回答1:


Here is the code I used to email charts. Please note that you need to give everyone with the link access to the spreadsheet. If not, you'll get an image in the email stating user is not signed in. (very annoying that there's no workaround to this)

function emailCharts(sheet,emails,emailSubject){
  var charts = sheet.getCharts();

  if(charts.length==0){
    MailApp.sendEmail({
      to: emails,
      subject: "ERROR:"+emailSubject,
      htmlBody: "No charts in the spreadsheet"});    
    return;
  }

  var chartBlobs=new Array(charts.length); 
  var emailBody="Charts<br>";
  var emailImages={};
  for(var i=0;i<charts.length;i++){
    chartBlobs[i]= charts[i].getAs("image/png").setName("chartBlob"+i);
    emailBody= emailBody + "<img src='cid:chart"+i+"'><br>";
    emailImages["chart"+i]= chartBlobs[i];
  }

  MailApp.sendEmail({
    to: emails,
    subject: emailSubject,
    htmlBody: emailBody,
    inlineImages:emailImages});

}



回答2:


Make the spreadsheet Public and run the script. Modified version of the script pasted below with comments

enter code here function 
emailCharts(sheet,emails,emailSubject){
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active        spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Sheet1'); // Change the sheet name 
var emailSubject = 'test';
var emails = 'test@test.com'; // your email ID
var charts = sheet.getCharts();


if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});    
return;
}

var chartBlobs=new Array(charts.length); 
var emailBody="Charts<br>";
var emailImages={};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i]= newchart.getAs('image/png');
emailBody= emailBody + "<p align='center'><img src='cid:chart"+i+"'></p>";
emailImages["chart"+i]= chartBlobs[i];
}

MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody,
inlineImages:emailImages});
}


来源:https://stackoverflow.com/questions/19999269/emailing-a-chart-from-a-google-spreadsheet-with-apps-script

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