如何在Google Form的分段标题中展示Google Sheet数据?
解决方案
核心思路
通过Google Apps Script结合表单分支功能,让用户选择客户后跳转至专属展示区域,动态显示对应门店位置,避免全局修改表单导致的多用户冲突问题。
步骤1:准备表单与表格结构
- 在Google表单中创建第一个问题,类型设为下拉菜单,标题为「选择客户」。
- 记录该问题的ID:点击问题右上角三个点 → 「获取项目ID」。
- 确保你的Google Spreadsheet表头为「客户」「位置」,数据格式与示例一致。
步骤2:编写Apps Script代码
打开表单的脚本编辑器(点击表单右上角三个点 → 「脚本编辑器」),粘贴以下代码并替换占位内容:
// 从表格获取客户与对应门店的映射关系 function getCustomerLocations() { // 替换为你的表格ID和工作表名称 const sheet = SpreadsheetApp.openById('你的Google Spreadsheet ID').getSheetByName('Sheet1'); const data = sheet.getDataRange().getValues(); const customerMap = {}; // 遍历表格数据,整理每个客户的门店列表 for (let i = 1; i < data.length; i++) { const customer = data[i][0]; const location = data[i][1]; if (!customerMap[customer]) { customerMap[customer] = []; } customerMap[customer].push(location); } // 将门店列表转为逗号分隔的字符串 for (const cust in customerMap) { customerMap[cust] = customerMap[cust].join(', '); } return customerMap; } // 更新表单的分支与展示内容 function updateFormBranches() { // 替换为你的Google Form ID const form = FormApp.openById('你的Google Form ID'); const customerMap = getCustomerLocations(); // 获取「选择客户」下拉框问题(替换为你的客户问题ID) const customerQuestion = form.getItemById('客户选择问题的ID').asMultipleChoiceItem(); // 删除表单中除第一题外的所有内容(避免重复生成分支) const items = form.getItems(); for (let i = 1; i < items.length; i++) { form.deleteItem(items[i]); } // 更新下拉框的客户选项(与表格同步) const choices = Object.keys(customerMap).map(cust => customerQuestion.createChoice(cust)); customerQuestion.setChoices(choices); // 为每个客户创建专属展示分支 for (const cust in customerMap) { const section = form.addSectionHeaderItem(); section.setTitle('您的门店位置'); section.setHelpText(customerMap[cust]); // 设置分支规则:选择该客户时跳转到当前展示区域 customerQuestion.setChoiceNavigation(customerQuestion.createChoice(cust), section); } }
步骤3:配置自动同步触发器
- 在脚本编辑器中,点击「编辑」→「当前项目的触发器」。
- 点击「添加触发器」,配置如下:
- 要运行的函数:
updateFormBranches - 事件源:「电子表格」
- 事件类型:「更改时」(表格数据更新时自动同步表单)
- 要运行的函数:
- 保存触发器并授权脚本所需权限。
步骤4:初始化表单
手动运行一次updateFormBranches函数(点击脚本编辑器中的运行按钮),生成所有客户对应的分支展示区域。
使用效果
用户打开表单选择客户后,会自动跳转到专属区域,看到该客户的所有门店位置(格式如:New York, San Jose)。后续表格中客户或门店数据更新时,触发器会自动同步表单内容。
内容的提问来源于stack exchange,提问作者user27373099
相关产品推荐
相关产品推荐

