Google Apps Script执行replaceText时抛出Invalid argument: replacement异常的解决求助
Google Apps Script执行replaceText时抛出Invalid argument: replacement异常的解决求助
各位好,我正在开发一个将Google Form数据转换为PDF并发送邮件的功能。目前的实现逻辑是先把表单收集到的数据存储到一个数组结构的对象中,再将这些内容填充到Google Doc模板里,最后导出为PDF。但在填充模板内容的环节一直抛出错误,实在找不到原因,来这里求助大家!
问题详情
当代码执行到替换模板文本的步骤时,会抛出以下错误:
Error Exception: Invalid argument: replacement
createPDF @ Code.gs:36
报错的具体行是body.replaceText("{ln}", info['Last Name'][1])。我一开始猜测是生日字段的问题——因为表单里的生日是日期类型,测试时我填了0,但后来把生日改成字符串后还是报错,说明问题不在这儿。
我的代码
function createPDF(){ // 预填充的表单测试数据 const info = { 'First Name' : ['Mike'], 'Last Name' : ['Wazowski'], 'Birthday' : [0], 'Email' : ['m@w.com'], 'Phone Number' : ['1'], 'Province' : ['Ontario'], 'Contact Method' : ['email'], 'Language': ['english'], 'Type Of Service': ['in person'], 'Child Name': [], 'Child Birthday': [], 'Services Required': ['counselling'], 'Staff Requested': ['Nancy'], 'Priority':['Health'], 'Referral': ['blank'], 'Jane Consent': ['Yes'], }; const pdfFolder = DriveApp.getFolderById("1g58GUQLPjPonsHtxj5LlxyoDgXs5wj2R"); const tempFolder = DriveApp.getFolderById("1Fkzf0xeZcedfq7BF2k3V4mn4Pz_LsXsv"); const templateDoc = DriveApp.getFileById("1eOqom8SqhuDUpIqYEVum-EvQ09cVz2d_XCLcRNAz8jE"); const newTempFile = templateDoc.makeCopy(tempFolder); const openDoc = DocumentApp.openById(newTempFile.getId()); const body = openDoc.getBody(); body.replaceText("{fn}", info['First Name'][0]); body.replaceText("{ln}", info['Last Name'][1]); /* 这一行抛出错误 */ body.replaceText("{bd}", info['Birthday'][2]); body.replaceText("{em}", info['Email'][3]); body.replaceText("{pn}", info['Phone Number'][4]); body.replaceText("{pv}", info['Province'][5]); body.replaceText("{cm}", info['Contact Method'][6]); body.replaceText("{lg}", info['Language'][7]); body.replaceText("{ts}", info['Type of Service'][8]); body.replaceText("{cn}", info['Child Name'][9]); body.replaceText("{cbd}", info['Child Birthday'][10]); body.replaceText("{sr}", info['Services Required'][11]); body.replaceText("{stf}", info['Staff Requested'][12]); body.replaceText("{pri}", info['Priority'][13]); body.replaceText("{ref}", info['Referral'][14]); body.replaceText("{jc}", info['Jane Consent'][15]); const blobPDF = newTempFile.getAs(MimeType.pdf); const pdfFile = pdfFolder.createFile(blobPDF).getName("Form Response"); }
补充说明
- 我是参照一个教程做的,教程里的代码能正常运行,但我的不行。对比下来,区别主要是我的表单字段更多,还有一个日期类型的字段。
- 测试时我把表单数据硬编码到了
info对象里,每个字段的值都是数组,部分字段是空数组(比如Child Name)。
希望大家能帮我找出问题所在,谢谢!
备注:内容来源于stack exchange,提问作者Sam Murdock
相关产品推荐
相关产品推荐

