如何用Google Apps Script将表格指定信息展示到网页(带权限验证)
极简实现方案
1. 后端脚本(Code.gs)
替换代码中的表格ID和工作表名称,用于获取用户数据并返回前端:
function doGet() { return HtmlService.createHtmlOutputFromFile('Index'); } function getUserData() { // 获取当前登录用户的邮箱 const userEmail = Session.getActiveUser().getEmail(); if (!userEmail) return { error: '无法获取用户邮箱,请确认已登录Google账号' }; // 替换为你的Google Sheets表格ID(URL中/d/和/edit之间的字符串) const spreadsheetId = '你的表格ID'; // 替换为你的工作表名称(比如Sheet1) const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName('Sheet1'); const data = sheet.getDataRange().getValues(); // 跳过表头,查找匹配邮箱的行 const userRow = data.slice(1).find(row => row[0] === userEmail); if (!userRow) { return { error: '未找到你的信息,请确认邮箱已绑定到公会表格' }; } // 返回需要提取的字段,索引对应表格列(0=Email,1=游戏昵称,2=Discord ID,3=Rank) return { inGameName: userRow[1], discordId: userRow[2], rank: userRow[3] }; }
2. 前端页面(Index.html)
自定义排版样式,加载时自动获取并渲染用户数据:
<!DOCTYPE html> <html> <head> <base target="_top"> <style> /* 可自定义样式,以下是示例 */ .container { max-width: 600px; margin: 3rem auto; padding: 2rem; font-family: Arial, sans-serif; background-color: #f8f9fa; border-radius: 8px; } .highlight { font-weight: bold; color: #2d3748; } .error { color: #e53e3e; font-weight: bold; } </style> </head> <body> <div class="container"> <div id="userContent"></div> </div> <script> // 页面加载时自动调用后端接口 window.onload = () => { google.script.run .withSuccessHandler(renderUserInfo) .withFailureHandler(showError) .getUserData(); }; // 渲染用户信息到页面 function renderUserInfo(data) { const contentDiv = document.getElementById('userContent'); if (data.error) { contentDiv.innerHTML = `<p class="error">${data.error}</p>`; return; } // 按需求排版文本,可自由修改结构 contentDiv.innerHTML = ` <p>您好,<span class="highlight">${data.inGameName}</span>!</p> <p>您绑定的Discord账号是<span class="highlight">${data.discordId}</span></p> <p>您的公会等级是<span class="highlight">${data.rank}</span></p> `; } // 加载失败提示 function showError(error) { document.getElementById('userContent').innerHTML = `<p class="error">加载失败:${error.message}</p>`; } </script> </body> </html>
3. 部署步骤
- 打开Google Apps Script(可直接在目标Google Sheets中点击「扩展」→「Apps Script」)
- 新建项目,删除默认代码,粘贴上述
Code.gs内容并替换表格ID和工作表名称 - 点击左侧「文件」→「新建」→「HTML」,命名为
Index,粘贴上述HTML代码 - 点击右上角「部署」→「新部署」,类型选择「Web应用」:
- 执行:选择你的Google账号
- 谁可以访问:选择「任何人使用Google账号登录」(满足私密性需求)
- 点击部署,复制生成的Web链接分享给社群成员即可
注意事项
- 首次部署/运行需完成Google授权流程,按提示操作即可
- 表格中「Email」列必须与用户登录的Google账号邮箱完全匹配
- 若需调整展示字段,修改
Code.gs中返回的对象属性,同步调整Index.html的渲染内容即可
内容的提问来源于stack exchange,提问作者Corinne Jacobo
相关产品推荐
相关产品推荐

