使用谷歌电子表格中的数据填写谷歌图表

时间:2014-02-03 20:02:24

标签: javascript google-apps-script

这似乎很简单,但我搜索过但没有找到解决方案。我正在尝试根据Google电子表格中的数据在我的网站上创建一个图表。我已经能够使用硬编码值使其工作但不确定如何从电子表格填充。

我当前的脚本如下所示:

  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }

我的电子表格上的数据与硬编码的内容相似,但我想给它一个电子表格网址,并从中填写(网址如下:https://docs.google.com/spreadsheet/ccc?key=0AnD0SFr9ooPgdG83Wm

1 个答案:

答案 0 :(得分:2)

这里有一个示例教程:

https://google-developers.appspot.com/chart/interactive/docs/spreadsheets

基本上,您的代码将如下所示:(我不确定您的网址是否正确。另外,请设置网址的末尾以使用正确的数据范围):

    google.load("visualization", "1", {packages:["corechart"]});

function initialize() {
        var opts = {sendMethod: 'auto'};
        // Replace the data source URL on next line with your data source URL.
        var query = new google.visualization.Query('http://spreadsheets.google.com/tq?key=0AnD0SFr9ooPgdG83Wm&transpose=0&headers=1&merge=COLS&range=A1%3AA5%2CB1%3AC5&gid=0&pub=1', opts);         
        -
        // Optional request to return only column C and the sum of column B, grouped by C members.
        //query.setQuery('select C, sum(B) group by C');

        // Send the query with a callback function.
        query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
      if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
      }

    var data = response.getDataTable();

  var options = {
    title: 'Company Performance'
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}

      google.setOnLoadCallback(initialize);