簡體   English   中英

如何使用javascript在谷歌表格中創建圖表?

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

我正在使用 javascript 來創建包含用戶數據的 Google-sheets-document。 該文檔保存在用戶的雲端硬盤中。 我不知道如何根據我插入的數據制作圖表。 我正在使用帶有 Google 表格 API 的 vanilla javascript。 它可能看起來像這樣:

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

編輯:要指定,我想將圖形插入我創建的工作表文檔,而不是網站。

參考這個例子

 <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>

來自https://developers.google.com/chart/interactive/docs/drawing_charts

如果您想將圖表添加到電子表格中,您可以使用 Sheets API 的AddChartRequest作為電子表格的一部分。batchUpdate方法。

代碼片段:

從廣義上講,您的請求將如下所示(請查看下面的參考資料以詳細構建請求正文):

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);

在瀏覽器和移動設備中渲染圖表:

如果您只想在瀏覽器中呈現圖表,但不想將其添加到電子表格中,則可以使用Google 圖表(例如,請參閱可視化:餅圖)。

參考:

我解決了。 謝謝您的幫助! 這對我有用。

    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