如何将2D数组作为Google电子表格图表的范围传递?

时间:2015-07-30 20:16:40

标签: google-apps-script google-sheets

让我们说:

A栏:

Cat
Dog
Pig

B栏:

2
3
4

添加新图表功能:

function newChart() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var activeRange = sheet.getActiveRange();

  var data = ss.getSheets()[0];

  Logger.log(activeRange.getValues())

  var chart = data.newChart()
     .setChartType(Charts.ChartType.PIE)
     .addRange(activeRange)
     .setPosition(3, 2, 0, 0)
     .setOption('title','Farm')
     .build();

  data.insertChart(chart);
}

单元格A1:B3中的activeRange; activeRange值(2D数组):

[15-07-30 15:59:02:865 EDT] [[Cat, 2.0], [Dog, 3.0], [Pig, 4.0]]

但是当我尝试将2D数组作为范围传递时

  var range = [['Cat', 2.0], ['Dog', 3.0], ['Pig', 4.0]];

  var chart = data.newChart()
     .setChartType(Charts.ChartType.PIE)
     .addRange(range)
     .setPosition(3, 2, 0, 0)
     .setOption('title','Farm')
     .build();

我收到了下一个错误:

  

无法将数组转换为范围。

请帮我弄清楚如何将2D数组作为范围传递。

2 个答案:

答案 0 :(得分:1)

您可以尝试通过将值设置为范围来将数组对象转换为范围。请检查以下代码:

function newChart() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var range = [['Cat', 2.0], ['Dog', 3.0], ['Pig', 4.0]];
  var activeRange = sheet.getRange(1, 1, 3, 2).setValues(range);
  var data = ss.getSheets()[0];
  var chart = data.newChart()
     .setChartType(Charts.ChartType.PIE)
     .addRange(activeRange)
     .setPosition(3, 2, 0, 0)
     .setOption('title','Farm')
     .build();

  data.insertChart(chart);
}

尝试并能够获取数组值的饼图。希望有所帮助!

答案 1 :(得分:0)

以防万一这对某人有用。从活动范围创建图表的简单功能:

  // global
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var activeRange = sheet.getActiveRange();

function newChart() {

  // Get values from Active Range:
  var source = activeRange.getValues();

  // Get only unique entries (uses 2D Arrays Library):
  var uniqueCount = ArrayLib.unique(source)

  // Some rearrangemen to get propper output:
  var sourceOutput = [];  
     for(var i = 0; i < uniqueCount.length; i++)
{
    sourceOutput = sourceOutput.concat(uniqueCount[i]);
}

  // Empty arr
  var empArr = new Array([]);

  var counts = {};    
     for(var i = 0; i< source.length; i++) {
        var num = source[i];   
       if(empArr < num){
    counts[num] = counts[num] ? counts[num]+1 : 1;
       }    
}

  var keyArray = Object.keys(counts).map(function (key) {return counts[key]});

  var output=[];
     for(i=0;i<sourceOutput.length;i++){
       output.push( [sourceOutput[i], keyArray[i] ]);
};

  Logger.log(output)

  // Create a chart
  var data = ss.getSheets()[0];  
  var outputRange=data.getRange(10, 1, uniqueCount.length, 2).setValues(output);  
  var chart = data.newChart()
     .setChartType(Charts.ChartType.PIE)
     .addRange(outputRange)
     .setPosition(3, 3, 0, 0)
     .setOption('title','%your_title%')
     .build();

  data.insertChart(chart);
}