Google Sheets宏合并需求:按单元格值建子文件夹并导出bof.cfg
解决方案:合并并优化Google Sheets宏
以下是合并后的createConfigs宏代码,实现需求的同时优化了原代码的冗余与稳定性:
function createConfigs() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const mainSheet = ss.getSheetByName('MAIN'); const bofSheet = ss.getSheetByName('IXRE-BOF'); // 读取核心配置参数并去除首尾空格 const parentFolderId = mainSheet.getRange('K25').getValue().trim(); const subFolderName = mainSheet.getRange('B9').getValue().trim(); // 校验必填参数,为空则终止操作并提示 if (!parentFolderId || !subFolderName) { SpreadsheetApp.getUi().alert('请确保父文件夹ID(K25)和子文件夹名称(B9)不为空!'); return; } try { // 尝试获取指定名称的子文件夹 const parentFolder = DriveApp.getFolderById(parentFolderId); let subFolder = parentFolder.getFoldersByName(subFolderName).next(); } catch (e) { // 子文件夹不存在时创建它 const parentFolder = DriveApp.getFolderById(parentFolderId); parentFolder.createFolder(subFolderName); SpreadsheetApp.getUi().alert(`已创建子文件夹:${subFolderName}`); } finally { // 确保获取到目标子文件夹(无论是否刚创建) const parentFolder = DriveApp.getFolderById(parentFolderId); const subFolder = parentFolder.getFoldersByName(subFolderName).next(); // 读取IXRE-BOF页A列数据,过滤空行 const bofData = bofSheet.getRange('A:A').getValues() .flat() .filter(content => content && content !== ''); // 无有效内容时提示并终止 if (bofData.length === 0) { SpreadsheetApp.getUi().alert('IXRE-BOF页A列没有可导出的有效内容!'); return; } // 将数组内容拼接为文本格式 const bofContent = bofData.join('\n'); // 处理文件覆盖:删除已存在的bof.cfg const existingBofFile = subFolder.getFilesByName('bof.cfg'); if (existingBofFile.hasNext()) { existingBofFile.next().setTrashed(true); // 移入回收站,也可改用remove()直接删除 } // 在子文件夹中创建/覆盖bof.cfg subFolder.createFile('bof.cfg', bofContent, MimeType.PLAIN_TEXT); SpreadsheetApp.getUi().alert(`配置文件已成功生成/覆盖至子文件夹:${subFolderName}`); } }
关键优化说明
- 参数校验:提前检查必填字段,避免无效API调用
- 文件夹逻辑简化:利用
getFoldersByName().next()的异常特性,用try-catch实现“查找或创建”,替代原代码可能的循环遍历,代码更简洁 - 文件覆盖实现:先查找并移除旧文件,再创建新文件,解决重复生成的问题
- 数据清洗:过滤A列空行,避免导出无效内容
- 错误处理:捕获文件夹不存在等异常,保证流程稳定性
- 用户反馈:通过弹窗明确告知操作结果,提升使用体验
- 代码复用:减少重复的文件夹ID获取操作,优化代码结构
内容的提问来源于stack exchange,提问作者cyberjax21
相关产品推荐
相关产品推荐

