如何将Google Sheet转JSON后的A1、A2单元格内容展示在HTML文档中?
如何将Google Sheet中的A1、A2单元格内容展示到HTML文档中
我来帮你搞定这个需求!核心思路就是通过前端JavaScript请求你提供的Google Sheet JSON Feed,解析返回的数据后,把对应的内容插入到HTML页面的指定位置。下面分两种方案给你演示:
方案一:原生JavaScript实现(无需额外依赖)
这种方法用浏览器原生的fetch API,不需要引入任何外部库,兼容性也很好。
完整代码示例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>展示Google Sheet内容</title> </head> <body> <!-- 用来展示A1和A2内容的容器 --> <div> <h4>A1单元格内容:</h4> <p id="cell-a1"></p> </div> <div> <h4>A2单元格内容:</h4> <p id="cell-a2"></p> </div> <script> // 你的Google Sheet JSON链接 const sheetJsonUrl = 'https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json'; // 请求并解析JSON数据 fetch(sheetJsonUrl) .then(response => { if (!response.ok) throw new Error('网络请求失败'); return response.json(); }) .then(data => { // 获取表格的所有数据行 const sheetRows = data.feed.entry; // 👉 这里是关键:根据你的表格结构调整键名 // 如果你没有设置表头(A1就是第一行数据),A列的键是`gsx$a` // 如果A1是表头文本(比如"内容"),那么键就是`gsx$内容` // 可以通过console.log(sheetRows[0])在浏览器控制台查看具体结构 console.log('表格数据结构:', sheetRows[0]); // 假设你的表格没有表头,A1是第一行数据,A2是第二行数据 const a1Content = sheetRows[0].gsx$a.$t; const a2Content = sheetRows[1].gsx$a.$t; // 将内容插入到页面元素中 document.getElementById('cell-a1').textContent = a1Content; document.getElementById('cell-a2').textContent = a2Content; }) .catch(error => { console.error('加载数据出错:', error); document.getElementById('cell-a1').textContent = '加载失败,请检查Sheet权限或网络'; document.getElementById('cell-a2').textContent = '加载失败,请检查Sheet权限或网络'; }); </script> </body> </html>
方案二:jQuery实现(代码更简洁)
如果你已经在项目中使用了jQuery,可以用$.getJSON简化代码:
完整代码示例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>展示Google Sheet内容</title> <!-- 引入jQuery库 --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> </head> <body> <div> <h4>A1单元格内容:</h4> <p id="cell-a1"></p> </div> <div> <h4>A2单元格内容:</h4> <p id="cell-a2"></p> </div> <script> const sheetJsonUrl = 'https://spreadsheets.google.com/feeds/list/18A7tTdRRIRe4rQedoee5PXj0iQdbVFCa2GVQx6p9ep8/od6/public/basic?alt=json'; $.getJSON(sheetJsonUrl, function(data) { const sheetRows = data.feed.entry; // 同样根据表格结构调整键名 const a1Content = sheetRows[0].gsx$a.$t; const a2Content = sheetRows[1].gsx$a.$t; $('#cell-a1').text(a1Content); $('#cell-a2').text(a2Content); }) .fail(function() { $('#cell-a1').text('加载失败'); $('#cell-a2').text('加载失败'); }); </script> </body> </html>
关键注意事项
- Sheet权限设置:确保你的Google Sheet已经设置为**「任何人都可以查看」**,否则前端会因为跨域或权限问题无法获取数据。
- 键名调整:如果你的A1单元格是表头(比如写了"备注"),那么数据里的键会是
gsx$备注,对应的内容是gsx$备注.$t。可以通过浏览器控制台打印sheetRows[0]来确认具体的键名。 - 跨域问题:只有公开可访问的Sheet才能被前端直接请求,私有Sheet需要通过后端代理或者Google API验证来获取数据。
内容的提问来源于stack exchange,提问作者Tane
相关产品推荐
相关产品推荐

