如何在复制处理后的文档时自定义重命名?附现有脚本
实现谷歌文档占位符替换并重命名复制
我需要从谷歌表格提取数据,替换谷歌文档中的占位词,将处理完成的文档复制到独立文件夹,同时给复制后的文件指定自定义名称,但多次尝试都没成功,现有Google Apps Script代码如下:
function myFunction() { const docFile = DriveApp.getFileById("1OLAGN_5NN1ZEudjlAjfnESu3auGHUxVHlwAktbm24OQ"); const tempFolder = DriveApp.getFolderById("10AU7yahd5PogWHK0m_mOUZvFS-pbu2g8"); const tempFile = docFile.makeCopy(tempFolder); const tempDocFile = DocumentApp.openById(tempFile.getId()); const body = tempDocFile.getBody(); var list = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var a = list.getRange(2, 3).getValue() var b = list.getRange(3, 3).getValue(); var c = list.getRange(4, 3).getValue(); body.replaceText("{Имя}", a); body.replaceText("{Дата}", b); body.replaceText("{Сумма}", c); tempDocFile.saveAndClose(); }
解决方案
要实现复制时重命名,有两种直接可行的方式:
方式一:复制时直接指定文件名
在调用makeCopy方法时,同时传入自定义文件名和目标文件夹,这是最高效的方式:
function myFunction() { const docFile = DriveApp.getFileById("1OLAGN_5NN1ZEudjlAjfnESu3auGHUxVHlwAktbm24OQ"); const tempFolder = DriveApp.getFolderById("10AU7yahd5PogWHK0m_mOUZvFS-pbu2g8"); // 获取表格数据,这里用姓名作为文件名的一部分,可按需调整 const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); const userName = sheet.getRange(2, 3).getValue(); const newFileName = `客户文档_${userName}`; // 自定义文件名格式 // 复制时直接设置新名称 const tempFile = docFile.makeCopy(newFileName, tempFolder); const tempDocFile = DocumentApp.openById(tempFile.getId()); const body = tempDocFile.getBody(); const date = sheet.getRange(3, 3).getValue(); const amount = sheet.getRange(4, 3).getValue(); body.replaceText("{Имя}", userName); body.replaceText("{Дата}", date); body.replaceText("{Сумма}", amount); tempDocFile.saveAndClose(); }
方式二:复制完成后再重命名
如果需要在替换文档内容后再确定文件名,可在保存文档后调用setName方法修改:
function myFunction() { const docFile = DriveApp.getFileById("1OLAGN_5NN1ZEudjlAjfnESu3auGHUxVHlwAktbm24OQ"); const tempFolder = DriveApp.getFolderById("10AU7yahd5PogWHK0m_mOUZvFS-pbu2g8"); // 先复制到目标文件夹 const tempFile = docFile.makeCopy(tempFolder); const tempDocFile = DocumentApp.openById(tempFile.getId()); const body = tempDocFile.getBody(); const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); const userName = sheet.getRange(2, 3).getValue(); const date = sheet.getRange(3, 3).getValue(); const amount = sheet.getRange(4, 3).getValue(); body.replaceText("{Имя}", userName); body.replaceText("{Дата}", date); body.replaceText("{Сумма}", amount); tempDocFile.saveAndClose(); // 替换完成后重命名文件 tempFile.setName(`订单文档_${userName}_${date}`); }
关键说明
- 文件名可以根据表格中的任意数据组合生成,比如姓名+日期+金额,只需调整
newFileName的字符串拼接逻辑 - 确保文件名符合谷歌云端硬盘的命名规则,避免特殊字符
- 两种方式都能实现需求,优先选择方式一,减少一次API调用
内容的提问来源于stack exchange,提问作者qqq
相关产品推荐
相关产品推荐

