簡體   English   中英

如何從網頁中的 Google Sheets 單元格讀取數據?

[英]How can I read data from a Google Sheets cell in my web page?

我有一個本地網頁index.html ,其中id="test"的 HTML 元素應該顯示一個特定單元格的內容,例如 A3 ("10"),來自這個 Google Spreadsheet

我以網頁的形式發布了它,但我不能 100% 確定它是否是我計划做的事情的最佳形式。

如何使用 JavaScript 在上面指定的元素中顯示 Google 電子表格中的選定單元格?

我不能依賴 PHP,因為我想將index.html文件放在我的計算機和手機上,而不需要實際托管它們。

根據 Matthew Lock 的回答,我已鏈接到 tabletop.js,它位於我的 JS 文件夾中。 此文件夾與索引文件位於同一級別。

    <script type="text/javascript" src="JS/tabletop.js"></script>

然后,在 JS 的主腳本標簽中,我包含了:

function init() {
     Tabletop.init( { key: '1kFFysrHSapJXr-DxdYbuaMzkg5iBP60jR6OBFgzwSds',
               callback: function(data, tabletop) { window.alert("data") },
               simpleSheet: true } )
    };

看它是否吐出什么東西。 它沒有。 甚至沒有簡單的“數據”警報。 我究竟做錯了什么?

這是我嘗試在JSFiddle 中構建的一個最小示例,但我想我在如何鏈接到 tabletop.js(在外部資源下)方面遇到了其他問題......

如果您想使用 javascript 從您自己的網頁中讀取 Google Docs/Drive 單元格,我推薦使用Tabletop.js庫:

<script type="text/javascript">
  window.onload = function() { init() };

  var public_spreadsheet_url = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html';

  function init() {
    Tabletop.init( { key: public_spreadsheet_url,
                     callback: showInfo,
                     simpleSheet: true } )
  }

  function showInfo(data, tabletop) {
    alert("Successfully processed!")
    console.log(data);
  }
</script>

showInfo 函數的數據參數將包含一個數組對象。 數組的每一行對應於電子表格中的一行,單元格將位於一個對象中,每個列標題作為名稱。 例如:

[ { name: "Carrot", category: "Vegetable", healthiness: "Adequate" }, 
  { name: "Pork Shoulder", category: "Meat", healthiness: "Questionable" }, 
  { name: "Bubblegum", category: "Candy", healthiness: "Super High"} ]

編寫文檔時的注意事項似乎不正確。 key 參數只需要來自公共電子表格 url 的鍵值,而不是整個 url。

這個問題已經老了。 我頁面上的工作方法現在是這樣的:

const spreadsheetId = 'xxxxxxYourSheetIdxxxxxx'
fetch(`https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:json`)
.then(res => res.text())
.then(text => {
    
    const jsonObj = JSON.parse(text.substr(47).slice(0, -2)).table.rows
    return jsonObj
    // I'm cutting off the first two rows (I think the letters A-Z and the categories) to get only clean table data

})
.then(json => {
    // console.dir(json) // see the returned JSON
    json.forEach(element => 
    {    
        // console.dir(element.c)  
        // Append to my own frontend 'events' collection:
        events.push(element.c)
    })
})

希望它可以幫助任何人。 這是一個黑客工具。 就我而言,存在嚴重的安全隱患,可寫的 G-Sheet 在前端可見。 其中一些應該移到后台。 無論如何,這是一個小項目,如果有人想破壞當地的藝術學校,我已經准備好備份內容。 它源於我對 DB 的無能,很快就會被更可靠的東西所取代。

暫無
暫無

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

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