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

Google Apps Script遍历对象替换文本出现replacement参数错误如何解决

报错原因
  • 数据类型不匹配:你之前使用e.namedValues获取表单提交数据时,API返回的每个字段值都是数组类型,所以你加[0]取数组第一个元素的写法是正确的。但切换为从表格行列读取数据后,你存入values对象的每个值都是单元格的原生值(字符串、数字、空值、布尔值等),并非数组,此时强行加[0]取值会出现异常:如果值为null/undefined/布尔值,取值结果会是undefined,而replaceText方法不允许传入undefined作为替换参数,直接触发你遇到的报错。
  • 拼写错误:你的替换代码里存在笔误{{Itme3}},正确应为{{Item3}},会导致该字段无法正常替换。
修复方案

批量替换实现

利用你values对象的键名和模板占位符{{键名}}的对应关系,直接遍历对象完成批量替换,无需手动编写几十行替换语句,同时兼容空值避免报错,只需将Create_PDF函数里所有手动替换的代码替换为以下逻辑即可:

// 遍历values对象批量替换所有占位符
for (const fieldKey in values) {
  const placeholder = `{{${fieldKey}}}`;
  // 空值兼容:如果值为null/undefined,替换为空字符串,避免参数错误
  const replaceVal = values[fieldKey] == null ? '' : values[fieldKey].toString();
  body.replaceText(placeholder, replaceVal);
}

修改后完整的Create_PDF函数参考:

function Create_PDF(values) {
  const PDF_folder = DriveApp.getFolderById("ID_1");
  const TEMP_FOLDER = DriveApp.getFolderById("ID_2");
  const PDF_Template = DriveApp.getFileById('ID_3');
  
  const newTempFile = PDF_Template.makeCopy(TEMP_FOLDER);
  const OpenDoc = DocumentApp.openById(newTempFile.getId());
  const body = OpenDoc.getBody();
  
  console.log(body);

  // 批量替换逻辑,替代原有几十行手动替换代码
  for (const fieldKey in values) {
    const placeholder = `{{${fieldKey}}}`;
    const replaceVal = values[fieldKey] == null ? '' : values[fieldKey].toString();
    body.replaceText(placeholder, replaceVal);
  }

  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;
}

内容的提问来源于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 02:45:07