简体   繁体   English

如何使用javascript在谷歌表格中创建图表?

[英]How to create chart in google sheets with javascript?

I am using javascript to create Google-sheets-document with user data.我正在使用 javascript 来创建包含用户数据的 Google-sheets-document。 The document is saved on the user's Drive.该文档保存在用户的云端硬盘中。 I can't figure out how to make a graph from the data i have inserted.我不知道如何根据我插入的数据制作图表。 I am using vanilla javascript with the Google sheets API.我正在使用带有 Google 表格 API 的 vanilla javascript。 It would probably look something like this:它可能看起来像这样:

  function createGraph() {
  
    gapi.client.sheets.graph
      .create({
        properties: {
          type(?): 'Pie'
          spreadsheetid: //some id
          range: 'A1:A10'
        },
      })
  }

EDIT: To specify, i want to insert the graph to the sheets-document that i have created, not to the website.编辑:要指定,我想将图形插入我创建的工作表文档,而不是网站。

Refer this example参考这个例子

 <html> <head> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js" ></script> <script type="text/javascript"> var data; var chart; // Load the Visualization API and the piechart package. google.charts.load("current", { packages: ["corechart"] }); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(drawChart); // Callback that creates and populates a data table, // instantiates the pie chart, passes in the data and // draws it. function drawChart() { // Create our data table. data = new google.visualization.DataTable(); data.addColumn("string", "Topping"); data.addColumn("number", "Slices"); data.addRows([ ["Mushrooms", 3], ["Onions", 1], ["Olives", 1], ["Zucchini", 1], ["Pepperoni", 2] ]); // Set chart options var options = { title: "How Much Pizza I Ate Last Night", width: 400, height: 300 }; // Instantiate and draw our chart, passing in some options. chart = new google.visualization.PieChart( document.getElementById("chart_div") ); chart.draw(data, options); } </script> </head> <body> <!--Div that will hold the pie chart--> <div id="chart_div" style="width: 400; height: 300;"></div> </body> </html>

Referred from https://developers.google.com/chart/interactive/docs/drawing_charts来自https://developers.google.com/chart/interactive/docs/drawing_charts

If you want to add the chart to your spreadsheet, you can use Sheets API's AddChartRequest , as part of the spreadsheets.batchUpdate method.如果您想将图表添加到电子表格中,您可以使用 Sheets API 的AddChartRequest作为电子表格的一部分。batchUpdate方法。

Code snippet:代码片段:

On broad terms, your request would look like this (check the reference below in order to build the request body in detail):从广义上讲,您的请求将如下所示(请查看下面的参考资料以详细构建请求正文):

const payload = {
    "requests": [
        {
            "addChart": {
                "chart": {
                    "spec": { // Chart type, range source, etc.
                        "pieChart": { // Pie chart specification
                          // object (PieChartSpec)
                        }
                        // rest of ChartSpec properties
                    },
                    "position": { // Where the chart will be located
                        // object (EmbeddedObjectPosition)
                    }
                }
            }
        }
    ]    
}

const params = {
    spreadsheetId = "YOUR-SPREADSHEET-ID",
    body = payload
}
gapi.client.sheets.spreadsheets.batchUpdate(params);

Render chart in browsers and mobile devices:在浏览器和移动设备中渲染图表:

In case you just wanted to render the chart in a browser, but not add it to your spreadsheet, you would use Google Charts (see Visualization: Pie Chart , for example).如果您只想在浏览器中呈现图表,但不想将其添加到电子表格中,则可以使用Google 图表(例如,请参阅可视化:饼图)。

Reference:参考:

I solved it.我解决了。 Thanks for the help!谢谢您的帮助! This worked for me.这对我有用。

    function createGraphv2(spreadsheetIdGraph, endIndex) {
  var params = {
    // The spreadsheet to apply the updates to.
    spreadsheetId: spreadsheetIdGraph, // TODO: Update placeholder value.
  };

  var batchUpdateSpreadsheetRequestBody = {
    // A list of updates to apply to the spreadsheet.
    // Requests will be applied in the order they are specified.
    // If any request is not valid, no requests will be applied.
    
        requests: [
          {
            addChart: {
              chart: {
                spec: {
                  title: 'Rapport',
                  basicChart: {
                    chartType: 'COLUMN',
                    legendPosition: 'BOTTOM_LEGEND',
                    axis: [
                      //X-AXIS
                      {
                        position: "BOTTOM_AXIS",
                        title: "FORBRUK"
                      },
                      //Y-AXIS
                      {
                        position: "LEFT_AXIS",
                        title: "TID"
                      }

                    ],

                    series: [
                      {
                        series: {
                          sourceRange: {
                            sources: [
                              {
                                sheetId: 0,
                                startRowIndex: 0,
                                endRowIndex: endIndex,
                                startColumnIndex: 5,
                                endColumnIndex: 6,
                              },
                            ],
                          },
                          
                        },
                        targetAxis: "LEFT_AXIS"
                      }
                    ]

                  }
                },
                position : {
                  newSheet : 'True'
                }
              },
             
            }
          }
        ],


    // TODO: Add desired properties to the request body.
  };

  var request = gapi.client.sheets.spreadsheets.batchUpdate(
    params,
    batchUpdateSpreadsheetRequestBody
  );
  request.then(
    function (response) {
      // TODO: Change code below to process the `response` object:
      console.log(response.result);
    },
    function (reason) {
      console.error("error: " + reason.result.error.message);
    }
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM