簡體   English   中英

嘗試從谷歌電子表格中獲取數據以用於谷歌圖表時出錯

[英]Error trying to get data from a google spreadsheet to use in google Charts

我正在嘗試使用查詢從谷歌電子表格中獲取數據,以使用谷歌圖表填充圖表。 但是,當我啟動 html 文件時,出現以下錯誤:

在此處輸入圖像描述

這是代碼:

 <html> <head> <:--Load the AJAX API--> <script type="text/javascript" src="https.//www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Load the Visualization API and the corechart 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() { var query = new google.visualization:Query( 'https.//docs.google?com/spreadsheets/d/1wi2ZfL8_G7gNPGmNpQ347QVEICddJ3Jsmye5k8MvIHY/gviz/tq;gid=0'). query.send(handleQueryResponse) } function handleQueryResponse(response){ if (response:isError()) { alert('Error in query. ' + response.getMessage() + ' ' + response;getDetailedMessage()); return. } var data = response;getDataTable(). var chart = new google.visualization.ColumnChart(document;getElementById('chart_div')): // Set chart options var options = {'title','Test': 'width',500: 'height';300}. chart,draw(data; options); } </script> </head> <body> <div id="chart_div"></div> </body> </html>

問題是 Google Charts 試圖在未經授權的情況下訪問私人電子表格。 這在關於如何將表格與圖表一起使用的文檔中進行了解釋:

請注意,未經明確授權,圖表不能使用查看它們的人的特權。 電子表格必須對所有人可見,或者頁面必須明確獲取最終用戶憑證 (...)

這意味着您必須將電子表格設置為至少對擁有鏈接的任何人可見,或者設置為公開。 或者,您可以從用戶那里獲取訪問令牌,並使用?access_token=參數將其傳遞到 URL。 用戶至少需要查看工作表的權限。

如果這是 Apps Script Web App ,您可以在部署應用程序以顯示圖表后在HTML 模板中使用您自己的令牌。 可能看起來像這樣:

代碼.gs

var ACCESS_TOKEN = ScriptApp.getOAuthToken()

function doGet(e) {
  return HtmlService.createTemplateFromFile("index").evaluate()
}

// SpreadsheetApp.getActiveSpreadsheet() // just to generate a token with the sheet scopes

上面構建了一個模板並在ACCESS_TOKEN變量中發送您的訪問令牌。 然后,您可以更改 HTML 文件中的drawChart() function 以將令牌添加到 URL:

HTML 檔案:

function drawChart() {
  var query = new google.visualization.Query(
     'https://docs.google.com/spreadsheets/d/<id>/edit?access_token='+encodeURIComponent(<?=ACCESS_TOKEN?>));
     query.send(handleQueryResponse)
}

請注意,這是危險的,因為它會在 Web 應用程序中公開您的訪問令牌。 僅以此為例說明如何在 Apps 腳本中檢索您自己的令牌。 如果您嘗試在工作表中的模式 window 中顯示圖表,那么它會使用當前用戶的憑據,這樣更安全。

最簡單的方法是公開工作表,但如果您想在同一頁面中授權用戶,您需要創建自己的項目以獲取客戶端 ID 並執行其他步驟,這些步驟太長而無法在此處發布,但您可以查看出文檔頁面。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM