将Google工作表图表导出为图像 [英] Export Google sheet Chart as an image
问题描述
请帮助您如何使用Google脚本将图表导出为图像.
Would you please help on how to export a chart to a image using google script.
我写了这段代码,但是没有用.我担心API getAs 已过时.
I wrote this code but it doesn't work. I'm worrying that the API getAs is deprecated.
function TestEmailCharts(){
var sheet = SpreadsheetApp.getActiveSheet();
var charts = sheet.getCharts();
if(charts.length!=0)
{
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/jpeg").setName("chartBlob"+i);
emailBody= emailBody + "<img src='cid:chart"+i+"'><br>";
emailImages["chart"+i]= chartBlobs[i];
}
MailApp.sendEmail({
to: "email@gmail.com",
subject: "test2",
htmlBody: emailBody,
inlineImages:emailImages});
}
}
要重现该问题,请创建一个Google电子表格 用一些数据创建一个简单的图表.
To reproduce the problem, create a Google spread sheet Create a simple chart with some data.
将此代码添加到脚本中. 用您的电子邮件替换email@gmail.com
Add this code to scripts. Replace email@gmail.com with your email
通常您会收到一封包含图表图像的电子邮件 但是问题是您将收到一封带有黑色图像的电子邮件.
Normally you should receive an email with chart image But the problem is that you will receive a email with black image.
最好的问候.
推荐答案
将Google表格图表导出为图像
通过电子邮件: 首先创建图表,然后获取其斑点.然后将Blob作为附件发送.
By Email: First create the chart and then get its blob. Then send the blob as attachment.
function createPieChart(){
var sheet = SpreadsheetApp.openById("<ID>").getSheetByName("<SheetName>");
var chartBuilder = sheet.newChart()
.asPieChart()
.set3D()
.addRange(sheet.getRange("A20").getDataRegion())
.setPosition(16, 5, 0, 0)
.setOption('title', "Total hour split in 2020");
var blob = chartBuilder.build().getBlob();
sendMail(blob);
}
function sendMail(img){
MailApp.sendEmail({
to: "john@domain.com",
subject: "test",
htmlBody: "fair enough",
attachments: [img]}); //If this gives you problems, replace img with img.getAs(MimeType.JPEG)
}
到另一个电子表格(与图表的源数据不同):
To another spreadsheet (different from where the source data for the chart is):
类似的方法,创建图表,然后将blob作为图像插入目标表中:
Similar way, create the chart and then insert the blob as an image in the destination sheet:
function createPieChart(){
var srcSheet = SpreadsheetApp.openById("<ID>").getSheetByName("<SheetName>");
var destSheet = SpreadsheetApp.openById("<ID>").getSheetByName("<SheetName>");
var chartBuilder = srcSheet.newChart()
.asPieChart()
.set3D()
.addRange(sheet.getRange("A20").getDataRegion())
.setPosition(16, 5, 0, 0)
.setOption('title', "Total hour split in 2020");
var blob = chartBuilder.build().getBlob();
destSheet.insertImage(blob, 1, 1);
}
这篇关于将Google工作表图表导出为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!