Google Apps Script:如何用Sheets多行数据填充Docs模板?
解决Google Apps Script批量填充Google Docs模板问题
原脚本核心问题
- 模板副本仅创建一次,循环内反复修改同一文档,后续行数据会覆盖之前的替换结果
- 数据范围冗余:硬编码获取24行6列,实际仅需前3列有效数据行
- 无效条件判断:
row[6] === 0引用不存在的列索引(表格仅4列,索引最大为3),判断逻辑失效 - 占位符替换错误:每次循环替换所有
{{Date1}}至{{Date5}}为当前行数据,导致所有占位符显示同一内容
方案1:将多行数据填充到同一文档的多组占位符(如一周考勤)
适用于把表格中多行数据对应填入模板的{{Date1}}、{{Date1in}}等系列占位符,生成单个汇总文档:
function fillWeeklyTemplate() { // 替换为你的实际ID const templateId = 'Google Docs模板ID'; const folderId = '目标文件夹ID'; const googleDocTemplate = DriveApp.getFileById(templateId); const destinationFolder = DriveApp.getFolderById(folderId); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('person'); // 获取有效数据:跳过表头,仅取前3列,自动识别最后一行数据 const rows = sheet.getRange(2, 1, sheet.getLastRow() - 1, 3).getValues(); // 创建单个模板副本并打开 const copy = googleDocTemplate.makeCopy('一周考勤记录', destinationFolder); const doc = DocumentApp.openById(copy.getId()); const body = doc.getBody(); // 循环每行数据,对应填充到DateN系列占位符 rows.forEach(function(row, index) { if (!row[0]) return; // 跳过空行 const rowNum = index + 1; const friendlyDate = new Date(row[0]).toLocaleDateString(); // 替换对应行的占位符 body.replaceText(`{{Date${rowNum}}}`, friendlyDate); body.replaceText(`{{Date${rowNum}in}}`, row[1]); body.replaceText(`{{Date${rowNum}out}}`, row[2]); }); doc.saveAndClose(); }
方案2:每行数据生成独立文档
适用于为表格中每行数据单独生成一个文档(如每日考勤文档):
function createDailyDocs() { // 替换为你的实际ID const templateId = 'Google Docs模板ID'; const folderId = '目标文件夹ID'; const googleDocTemplate = DriveApp.getFileById(templateId); const destinationFolder = DriveApp.getFolderById(folderId); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('person'); const rows = sheet.getRange(2, 1, sheet.getLastRow() - 1, 3).getValues(); rows.forEach(function(row) { if (!row[0]) return; // 跳过空行 const friendlyDate = new Date(row[0]).toLocaleDateString(); // 创建当前行的文档副本并命名 const copy = googleDocTemplate.makeCopy(`${friendlyDate} 考勤记录`, destinationFolder); const doc = DocumentApp.openById(copy.getId()); const body = doc.getBody(); // 替换模板中的单组占位符(需模板内有{{Date}}、{{TimeIn}}、{{TimeOut}}) body.replaceText('{{Date}}', friendlyDate); body.replaceText('{{TimeIn}}', row[1]); body.replaceText('{{TimeOut}}', row[2]); doc.saveAndClose(); }); }
使用注意事项
- 替换代码中的
Google Docs模板ID和目标文件夹ID为实际ID - 确保模板占位符与代码中定义的完全匹配
- 如需自定义日期格式,可修改
toLocaleDateString()参数,例如:toLocaleDateString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit'})
内容的提问来源于stack exchange,提问作者Hucosler
相关产品推荐
相关产品推荐

