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

Google Apps Script:含逗号的复选框值转Google Doc项目符号问题

解决Google表单多选复选框含逗号时生成Docs项目符号列表的问题

核心问题分析

Google表单的多选复选框若选项包含逗号,在Google Sheets中会用双引号包裹该选项(例如"Falls, car accidents, or any other accidents/injuries in past 3 months", Migraines)。直接用split(',')会错误拆分带逗号的选项,因此需要用正则匹配来正确解析。

解决方案

1. 编写解析函数处理带引号的多选字符串

创建函数,通过正则表达式提取每个选项,忽略选项内部的逗号:

function parseMultiSelectString(str) {
  if (!str || str.trim() === 'NONE') return [];
  const regex = /"([^"]*)"|([^,]+)/g;
  const matches = str.matchAll(regex);
  const options = [];
  for (const match of matches) {
    const option = match[1] || match[2];
    if (option) {
      options.push(option.trim());
    }
  }
  return options;
}

2. 修改createPDF_函数,生成项目符号列表

不再直接用replaceText替换占位符,而是定位占位符位置,删除后插入项目符号列表:

function createPDF_(row,sheet,response) {
   const head = sheet.getRange('1:1').getValues().flat()

   const posIncrement =  head.indexOf('[Form Publisher] Increment')
   const pos_pdfURL  =  head.indexOf('Response PDF URL')

   // 解析带逗号的多选字段
   const pastMHistoryRaw = response[`Past Medical History (Type 'NONE' below if there is no significant medical history)`][0];
   const pastMHistoryOptions = parseMultiSelectString(pastMHistoryRaw);
   
   const PAST_SURGICAL = response[`Past Surgical History (Type 'NONE' below if there is no significant surgical history)`][0]
   const MEDICATION_LIST = response[`Please list all medications you are currently taking (Type 'NONE' below if you are not taking medications)`][0] 
   const PROBLEM_LEN = response['How long have you been dealing with this problem?'][0] 
   const SEEN_TYPE = response['Do you prefer to be seen in person or have virtual (online) sessions?'][0] 
   const CONSENT = response[`Please click to download and read our "Attendance Policy, Privacy Policy, Financial Policy and Consent to Treat and click an answer below if you AGREE or DISAGREE to the policies as written here:`][0] 
   
   const today = new Date()
   const todays_Date_f = Utilities.formatDate(today,Session.getScriptTimeZone(),"MM dd yyyy") 
   const timestamp = Utilities.formatDate(today,Session.getScriptTimeZone(),"MM/dd/yyyy hh:mm:ss")
   const todaydate = Utilities.formatDate(today,Session.getScriptTimeZone(),"MM/dd/yyyy")
   const targetFolder = DriveApp.getFolderById(targetFolderID)
   const template = DriveApp.getFileById(templateID)
   
   const docFile = template.makeCopy(`Intake Form_${LAST_NAME}_${FIRST_NAME}`,targetFolder)
   const doc = DocumentApp.openById(docFile.getId())
   const body = doc.getBody()  
   const header = doc.getHeader()
   
   /** 替换普通文本占位符 */
   body.replaceText('<<Past Surgical History>>',PAST_SURGICAL)
   body.replaceText('<<List of Medication>>',MEDICATION_LIST)
   body.replaceText('<<Problem Duration>>',PROBLEM_LEN)
   body.replaceText('<<Session Type>>',SEEN_TYPE)
   body.replaceText('<<Consent>>',CONSENT)
   
   /** 处理多选字段,生成项目符号列表 */
   const placeholder = '<<Past Medical History>>';
   const element = body.findText(placeholder);
   if (element) {
     const parent = element.getElement().getParent();
     // 删除占位符文本
     parent.asText().deleteText(element.getStartOffset(), element.getEndOffsetInclusive());
     // 插入项目符号列表
     if (pastMHistoryOptions.length > 0) {
       pastMHistoryOptions.forEach(option => {
         body.insertListItem(parent.getChildIndex(parent), option).setGlyphType(DocumentApp.GlyphType.BULLET);
       });
     } else {
       // 无选项时插入NONE
       body.insertText(parent.getChildIndex(parent), 'NONE');
     }
   }
   
   doc.saveAndClose()
   
   var pdfBlob = doc.getAs('application/pdf');
   var pdfFile = targetFolder.createFile(pdfBlob);
   sheet.getRange(row,posIncrement+1).setValue(row+5)
   sheet.getRange(row,pos_pdfURL+1).setValue(pdfFile.getUrl())
   docFile.setTrashed(true)
}

3. 其他注意事项

  • 若存在多个带逗号的多选字段,重复上述解析和列表插入逻辑即可。
  • 确保模板中的多选字段占位符(如<<Past Medical History>>)为单独段落,避免与其他文本混合,方便准确定位删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:27:45