Google Apps Script技术问题:需将生成文档存入对应客户文件夹
解决Google Apps Script生成文档存入对应客户文件夹的问题
修改思路
核心是让生成文档的脚本能够根据每行的客户名称(D列,对应数组索引row[3])动态获取或创建目标文件夹,替代原来固定的文件夹ID配置。
修改后的完整脚本
// 检查文件夹是否存在,不存在则创建,返回文件夹对象 function checkIfFolderExistElseCreate(parent, folderName) { var folder; try { folder = parent.getFoldersByName(folderName).next(); } catch (e) { folder = parent.createFolder(folderName); } return folder; } // 批量预创建客户文件夹(可选,生成文档的脚本也会自动创建) function clientFolder() { var parent = DriveApp.getFolderById("你的父文件夹ID"); SpreadsheetApp.getActive().getSheetByName('Engagement Letter').getRange('D2:D').getValues() .forEach(function (r) { if(r[0]) checkIfFolderExistElseCreate(parent, r[0]); }); } // 生成文档并存入对应客户文件夹 function createEngagementLetter() { const googleDocTemplate = DriveApp.getFileById('你的模板文档ID'); const parentFolder = DriveApp.getFolderById("你的父文件夹ID"); // 和clientFolder中的父文件夹ID保持一致 const sheet = SpreadsheetApp .getActiveSpreadsheet() .getSheetByName('Engagement Letter'); const rows = sheet.getDataRange().getValues(); rows.forEach(function(row, index){ // 跳过表头行 if (index === 0) return; // 跳过已生成文档的行(A列已有链接) if (row[0]) return; const clientName = row[3]; // 获取当前客户对应的文件夹(不存在则自动创建) const clientFolder = checkIfFolderExistElseCreate(parentFolder, clientName); // 将模板复制到客户文件夹中 const copy = googleDocTemplate.makeCopy(`${clientName}, Letter of Engagement`, clientFolder); const doc = DocumentApp.openById(copy.getId()); const body = doc.getBody(); // 替换模板中的变量 body.replaceText('{{Client Email}}', row[1]); body.replaceText('{{Date}}', row[2]); body.replaceText('{{Client}}', row[3]); body.replaceText('{{Primary Point of Contact}}', row[4]); body.replaceText('{{PPOC Role}}', row[5]); body.replaceText('{{PPOC Email}}', row[6]); body.replaceText('{{PPOC First Name}}', row[7]); body.replaceText('{{Supervisor}}', row[8]); body.replaceText('{{Issues overview and what we will do}}', row[9]); body.replaceText('{{Discount}}', row[10]); body.replaceText('{{Initial Rate}}', row[11]); body.replaceText('{{Reason for Discount}}', row[12]); body.replaceText('{{Discount Amount}}', row[13]); body.replaceText('{{Overall Rate}}', row[14]); body.replaceText('{{Include Estimate}}', row[15]); body.replaceText('{{Estimate of Overall Cost}}', row[16]); // 保存并关闭文档 doc.saveAndClose(); // 将文档链接写入A列 const url = doc.getUrl(); sheet.getRange(index + 1, 1).setValue(url); }); }
关键修改点
- 完善文件夹检查函数:给
checkIfFolderExistElseCreate添加返回值,使其能返回找到或新建的文件夹对象,供生成文档时调用。 - 动态获取目标文件夹:在
createEngagementLetter中,不再使用固定的目标文件夹ID,而是通过父文件夹和当前行的客户名称,动态匹配对应文件夹。 - 直接存入目标文件夹:调用
makeCopy时,将目标参数改为动态获取的客户文件夹,确保文档直接存入对应客户目录。
内容的提问来源于stack exchange,提问作者Alec Aiken
相关产品推荐
相关产品推荐

