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