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

使用Google Apps Script将Google Sheet数据导入单个Google Docs文档

解决方案

你的代码当前为每行数据生成独立文档,要改成将所有数据合并到单个Google Docs,只需调整逻辑,让文档仅创建一次,再将所有行数据依次插入同一文档中。以下是修改后的代码:

function createSingleGoogleDoc() {
  // 模板文档ID
  const googleDocTemplate = DriveApp.getFileById('1kVXtatdcdlKRYzDADnIckSYcg8N3SIixn-6lEHsRMbk');
  // 存储目标文件夹ID
  const destinationFolder = DriveApp.getFolderById('1ZmfdojPXdBkW93EECH9rd9Vt06Cqx7tI');
  // 获取数据表格
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
  const rows = sheet.getDataRange().getValues();
  
  // 仅创建一个文档副本
  const copy = googleDocTemplate.makeCopy('所有文章详情汇总', destinationFolder);
  const doc = DocumentApp.openById(copy.getId());
  const body = doc.getBody();
  
  // 读取模板的原始内容作为记录模板,后续复用
  const templateElements = body.getChildren();
  const recordTemplate = [];
  templateElements.forEach(element => {
    recordTemplate.push(element.copy());
  });
  
  // 清空文档原始内容,准备插入所有数据
  body.clear();
  
  // 遍历所有数据行
  rows.forEach(function(row, index){
    // 跳过表头行
    if (index === 0) return;
    
    // 复制模板元素并替换内容
    recordTemplate.forEach(element => {
      const copiedElement = element.copy();
      if (copiedElement.getType() === DocumentApp.ElementType.PARAGRAPH) {
        const friendlyDate = new Date(row[1]).toLocaleDateString();
        copiedElement.replaceText('{{Headline}}', row[0]);
        copiedElement.replaceText('{{Timestamp}}', friendlyDate);
        copiedElement.replaceText('{{Article}}', row[2]);
        copiedElement.replaceText('{{CODR}}', row[3]);
        copiedElement.replaceText('{{URL}}', row[4]);
      }
      body.appendElement(copiedElement);
    });
    // 每个记录之间添加分隔线,增强可读性
    body.appendHorizontalRule();
  });
  
  // 保存并关闭文档
  doc.saveAndClose();
  const url = doc.getUrl();
  
  // 将文档链接写入表格的第6列(所有数据行)
  sheet.getRange(2, 6, rows.length - 1, 1).setValue(url);
}

关键修改说明

  • 文档创建逻辑:将模板副本的创建移到循环外,仅生成一个汇总文档
  • 模板复用:先读取模板的原始内容作为记录模板,每次遍历数据行时复制该模板并替换内容,保证格式统一
  • 内容合并:清空文档原始内容后,依次插入所有数据行对应的内容,添加分隔线区分不同记录
  • 链接写入:处理完所有数据后,将同一个文档链接批量写入所有数据行的第6列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:25:32