如何使用Google App Script批量共享文档并可选是否发送通知
批量共享Google Sheets脚本实现方案
前置准备
- 存放共享数据的表格需满足如下结构:A列为待共享的Google Sheets完整链接,B列为接收邮箱列表,多个邮箱用英文逗号分隔,第1行为表头,实际共享数据从第2行开始
- 运行脚本前需完成权限授权,确保你对所有待共享的表格拥有所有者或编辑权限
版本1:共享时不发送邮件通知
function batchShareFilesNoNotification() { // 获取当前活动数据表 const dataSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 读取所有数据,跳过首行表头 const dataRows = dataSheet.getDataRange().getValues().slice(1); dataRows.forEach(row => { const fileLink = row[0]; const emailListStr = row[1]; // 跳过空数据行 if (!fileLink || !emailListStr) return; // 从链接中提取文件ID const fileId = fileLink.match(/\/d\/([a-zA-Z0-9-_]+)/)[1]; const targetFile = DriveApp.getFileById(fileId); // 拆分并清洗邮箱地址 const emailList = emailListStr.split(',').map(email => email.trim()).filter(email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)); // 批量添加编辑权限,关闭邮件通知 targetFile.addEditors(emailList, {sendNotificationEmails: false}); // 若需要设置仅查看权限,替换为下行代码 // targetFile.addViewers(emailList, {sendNotificationEmails: false}); // 若需要设置仅评论权限,替换为下行代码 // targetFile.addCommenters(emailList, {sendNotificationEmails: false}); }); }
版本2:共享时发送官方邮件通知
function batchShareFilesWithNotification() { // 获取当前活动数据表 const dataSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 读取所有数据,跳过首行表头 const dataRows = dataSheet.getDataRange().getValues().slice(1); dataRows.forEach(row => { const fileLink = row[0]; const emailListStr = row[1]; // 跳过空数据行 if (!fileLink || !emailListStr) return; // 从链接中提取文件ID const fileId = fileLink.match(/\/d\/([a-zA-Z0-9-_]+)/)[1]; const targetFile = DriveApp.getFileById(fileId); // 拆分并清洗邮箱地址 const emailList = emailListStr.split(',').map(email => email.trim()).filter(email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)); // 批量添加编辑权限,发送官方共享通知邮件 targetFile.addEditors(emailList); // 若需要设置仅查看权限,替换为下行代码 // targetFile.addViewers(emailList); // 若需要设置仅评论权限,替换为下行代码 // targetFile.addCommenters(emailList); }); }
操作步骤
- 打开存放共享数据的Google表格,点击顶部菜单栏「扩展程序」-「Apps 脚本」进入脚本编辑器
- 删除编辑器默认生成的代码,粘贴对应版本的脚本代码
- 点击保存按钮,自定义命名项目,首次运行时按提示完成权限授权
- 点击运行按钮执行对应函数即可完成批量共享
注意事项
- 单次批量共享的数量不要超过Google Apps Script的每日配额限制,避免触发限流
- 若邮箱格式校验失败会自动跳过该邮箱,可在运行结束后查看执行日志确认共享结果
内容的提问来源于stack exchange,提问作者Nadila
相关产品推荐
相关产品推荐

