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

如何将所有表头及计算列数据和namedValues一同加入Google Form转PDF的构造信息

解决方案

核心逻辑是利用表单提交事件自带的行位置信息,读取关联工作表中当前提交行的所有列(包含公式计算列)的内容,合并到你现有的info对象中即可。

修改后的完整代码

// 需先确认表单绑定的工作表第一行是所有列的表头(包括计算列的表头)
function After_Submit(e){
  // 原有表单提交的原始数据
  const info = e.namedValues;
  // ========== 新增:读取整行所有列数据(含计算列) ==========
  const submitSheet = e.range.getSheet();
  // 读取第一行表头
  const allHeaders = submitSheet.getRange(1, 1, 1, submitSheet.getLastColumn()).getDisplayValues()[0];
  // 读取当前提交行的所有列内容
  const currentRowValues = submitSheet.getRange(e.range.rowStart, 1, 1, submitSheet.getLastColumn()).getDisplayValues()[0];
  // 把所有列的表头和对应值合并到info对象,保持和原有namedValues相同的数组格式,兼容原有代码
  allHeaders.forEach((header, index) => {
    info[header] = [currentRowValues[index]];
  });
  // ========== 新增部分结束 ==========
  const pdfFile = Create_PDF(info);  
  console.log(info);
  sendEmail(info['Email Address to Receive file'][0],pdfFile);  
}

function sendEmail(email,pdfFile){
  GmailApp.sendEmail(email, "Subject", "File Attached", {
    attachments: [pdfFile], 
    name: "PDF Sender"
  });
}

function Create_PDF(info) {
  const PDF_folder = DriveApp.getFolderById("Storage destination ID");
  const TEMP_FOLDER = DriveApp.getFolderById("Temp Folder ID");
  const PDF_Template = DriveApp.getFileById('template ID');
  
  const newTempFile = PDF_Template.makeCopy(TEMP_FOLDER);
  const OpenDoc = DocumentApp.openById(newTempFile.getId());
  const body = OpenDoc.getBody();
  
  console.log(body);
  // 原有表单字段调用方式不变
  body.replaceText("{{value1}}", info['value1'][0])
  body.replaceText("{{value2}}", info['value2'][0]);
  body.replaceText("{{value3}}", info['value3'][0]);
  // 新增计算列直接调用即可,比如你计算列表头叫「累计得分」,模板里写{{累计得分}},就加下面这行
  // body.replaceText("{{累计得分}}", info['累计得分'][0]);

  OpenDoc.saveAndClose();
  
  const BLOBPDF = newTempFile.getAs(MimeType.PDF);
  const pdfFile =  PDF_folder.createFile(BLOBPDF).setName("FLHA");
  console.log("The file has been created ");
  
  return pdfFile;
}

注意事项

  • 确保表单绑定的工作表第一行是完整表头,包括所有计算列的表头,表头名称不要有多余空格、特殊字符差异
  • 如果你的计算列是由其他触发脚本生成、不是即时计算的数组公式,可以在读取行数据前加一行Utilities.sleep(1000)等待1秒,避免读取到未计算完成的空值
  • 所有列合并后调用方式和原有表单字段完全一致,直接用表头作为info的key即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:54:01