如何在Google Drive新建文件夹时自动向Google Sheet添加行?
实现Google Drive文件夹新增子文件夹时自动更新Google Sheet
步骤说明
- 打开与目标Google Sheet绑定的Google Apps Script(点击Sheet右上角「扩展程序」→「Apps Script」)
- 替换代码中的
TARGET_FOLDER_ID和TARGET_SHEET_ID为你的实际ID - 创建一个「 onChange 」类型的触发器,关联到脚本中的
handleFolderCreation函数
完整代码
// 替换为你的目标Drive文件夹ID const TARGET_FOLDER_ID = "你的文件夹ID"; // 替换为你的目标Google Sheet ID const TARGET_SHEET_ID = "你的表格ID"; function handleFolderCreation(e) { // 仅处理文件夹创建事件 if (e.changeType !== "CREATE") return; const createdItem = DriveApp.getFileById(e.source.getId()); // 验证是否为文件夹,且属于目标父文件夹 if (!createdItem.isFolder()) return; const parentFolders = createdItem.getParents(); if (!parentFolders.hasNext() || parentFolders.next().getId() !== TARGET_FOLDER_ID) return; // 获取新文件夹的关键信息 const folderName = createdItem.getName(); const folderUrl = createdItem.getUrl(); // 获取本地创建日期(转换为Sheet可识别的日期格式) const creationDate = Utilities.formatDate(createdItem.getDateCreated(), Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm:ss"); // 获取父文件夹名称 const parentFolderName = DriveApp.getFolderById(TARGET_FOLDER_ID).getName(); // 写入Google Sheet const sheet = SpreadsheetApp.openById(TARGET_SHEET_ID).getActiveSheet(); const lastRow = sheet.getLastRow(); // 构造要插入的行数据(空列用""占位,确保对应到E、G、M列) const newRow = Array(13).fill(""); // M列是第13列,所以创建13个元素的数组 newRow[4] = `=HYPERLINK("${folderUrl}", "${folderName}")`; // E列是第5列(索引从0开始) newRow[6] = creationDate; // G列是第7列 newRow[12] = parentFolderName; // M列是第13列 // 在末尾追加行 sheet.getRange(lastRow + 1, 1, 1, 13).setValues([newRow]); }
关键细节说明
- 触发器设置:在Apps Script的「编辑」→「当前项目的触发器」中,添加新触发器:选择
handleFolderCreation函数,事件源选「从驱动器」,事件类型选「更改」 - 日期格式:
Utilities.formatDate可以根据需求调整格式,比如只保留日期可以用"yyyy-MM-dd" - 列索引对应:数组索引从0开始,所以E列对应索引4,G列对应6,M列对应12,空列用空字符串占位保证列对齐
- 权限验证:首次运行脚本时需要授权,确保脚本有访问Drive和Sheet的权限
内容的提问来源于stack exchange,提问作者Mohammed Elshemy
相关产品推荐
相关产品推荐

