You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Apps Script实现Google Sheets全数据行导入Google Docs模板

问题原因

你的代码逻辑存在核心问题:第一次循环时,body.replaceText()会将文档中所有{{onTapName}}、{{onTapDescription}}、{{onTapPrice}}占位符全部替换为第一行数据。后续循环中,文档内已无这些占位符,自然无法替换后续行的内容。

解决方案

需要为每一行数据单独生成对应的条目区块,而非全局替换占位符。假设你的Google Docs模板里有一个包含三个占位符的段落(或文本块)作为单条啤酒数据的模板,我们可以复制这个模板块,为每一行数据生成新条目并替换其中的占位符。

修改后的完整代码
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  const menu = ui.createMenu('Print Menu');
  menu.addItem('Create New Print Menu', 'createNewMenu')
  menu.addToUi();
}

function createNewMenu() {
  // Google Doc Template ID and Save Destination
  const googleDocTemplate = DriveApp.getFileById('1xzlvVOSW_LsgOrm2N2o1-FKYzfqp_2EAbhqrLTn53yk');
  const destinationFolder = DriveApp.getFolderById('11HU0TvSPMMXUZaK5gTgg8jvofxTTt02j');

  // Get spreadsheet data
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Draft List');
  const rows = sheet.getDataRange().getValues();
  if (rows.length <= 1) return; // Exit if no data rows

  // Generate filename with current date
  const dateData = new Date();
  const curr_date = dateData.getDate();
  const curr_month = dateData.getMonth() + 1; // Months are zero-based
  const curr_year = dateData.getFullYear();
  const theDate = `${curr_year}-${curr_month}-${curr_date}`;
  const newFileName = `${theDate} - Bar Print Menu`;

  // Create copy of template document
  const copy = googleDocTemplate.makeCopy(newFileName, destinationFolder);
  const doc = DocumentApp.openById(copy.getId());
  const body = doc.getBody();

  // Locate the template paragraph containing placeholders
  const templateElement = body.findText('{{onTapName}}').getElement();
  const templateParagraph = templateElement.getParent();

  // Iterate through data rows (skip header row)
  for (let i = 1; i < rows.length; i++) {
    const rowData = rows[i];
    let targetParagraph;

    if (i === 1) {
      // Use original template paragraph for first data row
      targetParagraph = templateParagraph;
    } else {
      // Copy template paragraph and append to document for subsequent rows
      targetParagraph = templateParagraph.copy();
      body.appendParagraph(targetParagraph);
    }

    // Replace placeholders in current paragraph
    targetParagraph.replaceText('{{onTapName}}', rowData[0]);
    targetParagraph.replaceText('{{onTapDescription}}', rowData[1]);
    targetParagraph.replaceText('{{onTapPrice}}', rowData[2]);
  }

  doc.saveAndClose();
}
额外说明
  • 如果你的模板中啤酒条目是更复杂的结构(如表格行、带格式的文本块),只需将templateParagraph替换为对应的父元素(如TableRow),复制和替换逻辑保持一致。
  • 代码默认跳过第一行(表头),若你的数据无表头,可将循环起始的i = 1改为i = 0。

内容的提问来源于stack exchange,提问作者UserTHX1138

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 09:45:41