编程语言
首页 > 编程语言> > javascript-使用Google脚本在Google文档中复制图表

javascript-使用Google脚本在Google文档中复制图表

作者:互联网

我在Google文档(Google工作表)中建立了图表.现在,我需要复制图表. Google文档未提供图表的本地复制/粘贴界面.我试图在谷歌脚本中做到这一点没有运气:

function copyChart() {

var sheet = SpreadsheetApp.getActiveSheet();
var chart = sheet.getCharts()[0];
var chartCopy = sheet.newChart();
chartCopy = chart;
sheet.insertChart(chartCopy);

 }

如何制作可重复当前电子表格中第一个图表的工作脚本?

解决方法:

使用电子表格服务的当前状态,无法完全复制现有的EmbeddedChart.但是,可以复制图表的一部分,然后设置其余选项.

如果/当API变得更完整时,可以扩展此实用程序功能. (或者,如果Google完美克隆,它可能会过时!)

/**
 * 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的这一部分如此不足真的很可惜.

标签:google-sheets,google-apps-script,javascript
来源: https://codeday.me/bug/20191122/2062775.html