如何用Google Apps Script生成Google Sheets表单响应工作日重复行
用Google Apps Script处理表单公告的工作日重复展示需求
我通过Google Form收集用户提交的每日公告,部分公告仅需展示1天,部分需在多个工作日重复展示。需要借助Google Apps Script处理FORM RESPONSES 1工作表的表单响应数据,根据「重复天数」列的数值,生成包含后续工作日日期的重复行项,且仅在工作日生成重复行(例如日期从8/30直接跳至9/02,跳过周末)。
原工作表:FORM RESPONSES 1
| A | B | C | D | E |
|---|---|---|---|---|
| 时间戳 | 电子邮箱 | 公告日期 | 公告内容 | 重复天数 |
| 8/26/2024 04:08:31 | abc@yahoo.com | 08/29/2024 | Good luck... | 3 |
| 8/28/2024 14:08:31 | def@yahoo.com | 08/30/2024 | Join our club... | 2 |
期望生成效果
| A | B | C | D | E |
|---|---|---|---|---|
| 时间戳 | 电子邮箱 | 公告日期 | 公告内容 | 重复天数 |
| 8/26/2024 04:08:31 | abc@yahoo.com | 08/29/2024 | Good luck... | 3 |
| 8/26/2024 04:08:31 | abc@yahoo.com | 08/30/2024 | Good luck... | 3 |
| 8/28/2024 14:08:31 | def@yahoo.com | 08/30/2024 | Join our club... | 2 |
| 8/26/2024 04:08:31 | abc@yahoo.com | 09/02/2024 | Good luck... | 3 |
| 8/28/2024 14:08:31 | def@yahoo.com | 09/02/2024 | Join our club... | 2 |
解决方案:Google Apps Script 代码
以下脚本读取原始表单数据,自动生成符合要求的工作日重复行,并将结果写入新工作表(避免修改原始数据):
function generateRepeatedAnnouncements() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sourceSheet = ss.getSheetByName("FORM RESPONSES 1"); const targetSheet = ss.getSheetByName("生成的公告") || ss.insertSheet("生成的公告"); // 清空目标表现有内容,保留表头 targetSheet.clearContents(); const header = sourceSheet.getRange(1, 1, 1, sourceSheet.getLastColumn()).getValues()[0]; targetSheet.getRange(1, 1, 1, header.length).setValues([header]); // 获取原始数据(跳过表头) const data = sourceSheet.getRange(2, 1, sourceSheet.getLastRow() - 1, sourceSheet.getLastColumn()).getValues(); let outputRows = []; data.forEach(row => { const timestamp = row[0]; const email = row[1]; let currentDate = new Date(row[2]); const content = row[3]; const repeatCount = parseInt(row[4]); // 生成指定天数的工作日行(含初始日期) for (let i = 0; i < repeatCount; i++) { // 跳过周末,找到下一个工作日 while (currentDate.getDay() === 0 || currentDate.getDay() === 6) { currentDate.setDate(currentDate.getDate() + 1); } // 格式化日期为MM/dd/yyyy格式 const formattedDate = Utilities.formatDate(currentDate, Session.getScriptTimeZone(), "MM/dd/yyyy"); outputRows.push([timestamp, email, formattedDate, content, repeatCount]); // 日期加1,进入下一轮检查 currentDate.setDate(currentDate.getDate() + 1); } }); // 将结果写入目标工作表 if (outputRows.length > 0) { targetSheet.getRange(2, 1, outputRows.length, outputRows[0].length).setValues(outputRows); } SpreadsheetApp.getUi().alert("公告重复生成完成!"); }
使用步骤
- 打开目标Google表格,点击「扩展程序」→「Apps脚本」
- 将上述代码粘贴到脚本编辑器,保存并运行(首次运行需完成授权)
- 脚本会自动创建「生成的公告」工作表,包含所有按工作日重复的公告行
- 若需表单提交后自动运行,可在脚本编辑器的「触发器」菜单中,创建新触发器:选择
generateRepeatedAnnouncements函数,触发事件设为「表单提交」
内容的提问来源于stack exchange,提问作者Jennifer Razzaboni
相关产品推荐
相关产品推荐

