Google Apps Script:HTML表单触发VLOOKUP并返回结果+日志记录
实现VLOOKUP并返回学生姓名到HTML页面
1. 修改HTML表单的交互逻辑
调整前端按钮的点击事件,新增处理函数,在调用已有的acceptData()后,通过google.script.run调用后端查询函数,接收返回结果并展示:
<form> <input type="text" id="studentID" placeholder="输入学生ID"> <button type="button" onclick="handleCheckID()">Check ID</button> <div id="confirmationMsg"></div> </form> <script> function handleCheckID() { const studentID = document.getElementById('studentID').value; // 先执行已有的记录逻辑 acceptData(studentID); // 调用后端查询函数,成功后渲染结果 google.script.run .withSuccessHandler(function(name) { const msgEl = document.getElementById('confirmationMsg'); if (name) { msgEl.textContent = `确认:学生姓名为 ${name}`; msgEl.style.color = 'green'; } else { msgEl.textContent = '未找到匹配的学生ID'; msgEl.style.color = 'red'; } }) .getStudentName(studentID); } // 你的原有acceptData函数 function acceptData(studentID) { google.script.run.saveToLog(studentID); } </script>
2. 编写后端Google Apps Script查询函数
在脚本编辑器中新增getStudentName函数,实现从Database工作表中匹配学生姓名:
function getStudentName(studentID) { const ss = SpreadsheetApp.getActiveSpreadsheet(); const dbSheet = ss.getSheetByName('Database'); if (!dbSheet) return null; // 获取表内所有数据(假设ID在A列,姓名在B列) const data = dbSheet.getDataRange().getValues(); // 遍历查找匹配ID(跳过表头行) for (let i = 1; i < data.length; i++) { if (data[i][0] == studentID) { return data[i][1]; } } return null; }
可选:用VLOOKUP公式实现(不推荐)
如果偏好使用公式,可替换为以下代码,但遍历数组的方式无需依赖临时单元格,效率更高:
function getStudentName(studentID) { const ss = SpreadsheetApp.getActiveSpreadsheet(); const dbSheet = ss.getSheetByName('Database'); if (!dbSheet) return null; const tempCell = ss.getRange('Z1'); // 用一个临时单元格执行公式 tempCell.setFormula(`=VLOOKUP("${studentID}", Database!A:B, 2, FALSE)`); const result = tempCell.getValue(); tempCell.clearContent(); return result === '#N/A' ? null : result; }
注意事项
- 若ID和姓名的列位置不同,只需修改代码中
data[i][0](ID列索引)和data[i][1](姓名列索引)的数值(索引从0开始)。
内容的提问来源于stack exchange,提问作者San
相关产品推荐
相关产品推荐

