在电子表格服务的当前状态下,无法完全复制现有的 EmbeddedChart。但是,可以复制图表的一部分,然后设置其余选项。
如果/当 API 变得更完整时,可以扩展此实用程序功能。(或者如果谷歌完美克隆它可能会被淘汰!)
/**
* Returns a new EmbeddedChart instance with some properties
* replicated from the original.
*
* @param {EmbeddedChart} original source chart to be cloned
* @returns {EmbeddedChart} new, cloned chart
*/
function cloneChart( original ) {
original = original.modify(); // Necessary for read-access to some properties(!)
var clone = SpreadsheetApp.getActiveSheet().newChart();
// Set chart type
clone.setChartType(original.getChartType());
// Set position - caller should provide unique position
var originalContainer = original.getContainer();
var originalPostion = { anchorRowPos: originalContainer.getAnchorRow(),
anchorColPos: originalContainer.getAnchorColumn(),
offsetX: originalContainer.getOffsetX(),
offsetY: originalContainer.getOffsetY()
};
clone.setPosition(originalPostion.anchorRowPos,
originalPostion.anchorColPos,
originalPostion.offsetX,
originalPostion.offsetY);
// Copy ranges
var ranges = original.getRanges();
for (r=0; r<ranges.length; r++) {
clone.addRange(ranges[r]);
}
return clone.build();
}
例如:
function copyChart() {
var ss = SpreadsheetApp.getActive();
var sheet = SpreadsheetApp.getActiveSheet();
var chart = sheet.getCharts()[0];
var newChart = cloneChart(chart,customLineChart);
sheet.insertChart(newChart);
var numcharts = sheet.getCharts().length;
debugger;
return;
var chartBlob = chart.getBlob();
var builder = sheet.newChart();
chartCopy = chart;
sheet.insertChart(chartCopy);
}
/*
* Customize settings for line charts
*/
function customLineChart( chartBuilder ) {
chartBuilder.asLineChart()
.setTitle('Chart Title (Copy)')
.setOption('legend', {position: 'right', textStyle: {fontSize: 16}})
.setOption('height', 350)
.setOption('width', 450);
// ....
}
它不完整,但它是一个开始。API的这部分内容如此不足,真是太可惜了。