You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

禁用共享文档自动通知:Google Sheet批量添加编辑器报错求助

解决Google Apps Script共享文件的两个错误

错误原因分析

  1. Drive is not defined:你调用了Drive.Permissions.create但未启用Google Apps Script的高级Drive服务,该服务需要手动启用才能访问。
  2. Invalid argument: permission.value:
    • 循环索引错误:data数组从0开始,你的循环i=1;i<=data.length;i++会在i=data.length时访问undefined的数组元素,引发参数异常。
    • 空值未处理:当B/C列(对应收件人)为空时,destinataireEd1或destinataireEd2未定义,直接调用forEach会报错。
    • 重复操作:你同时使用fichier.addEditor(mail)和Drive.Permissions.create,前者默认发送通知,且重复添加权限可能触发错误。

修复步骤

1. 启用高级Drive服务

打开脚本编辑器,点击左侧菜单栏的服务→ 点击添加服务→ 找到Drive API,选择后点击添加。

2. 修复后的代码

function partagerFichiers() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("Feuille 1");
  if (!sheet) {
    Logger.log("找不到名为'Feuille 1'的工作表");
    return;
  }
  const data = sheet.getDataRange().getValues();
  
  // 从第二行开始遍历(跳过表头)
  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const fichierUrl = row[0]?.trim();
    // 对应B列(索引1)、C列(索引2)的收件人
    const destinataireEd1 = row[1]?.trim() ? row[1].split(";").map(item => item.trim()).filter(mail => mail) : [];
    const destinataireEd2 = row[2]?.trim() ? row[2].split(";").map(item => item.trim()).filter(mail => mail) : [];
    
    // 跳过无文件URL的行
    if (!fichierUrl) continue;

    try {
      // 提取文件ID
      const fichierId = fichierUrl.replace(/.*\/d\//, '').replace(/\/.*/, '');
      if (!fichierId) {
        Logger.log("无效的文件URL: " + fichierUrl);
        continue;
      }

      // 合并收件人并去重,避免重复添加权限
      const allEditors = [...new Set([...destinataireEd1, ...destinataireEd2])];
      if (allEditors.length === 0) {
        Logger.log("行" + (i+1) + "无有效收件人");
        continue;
      }

      // 批量添加编辑器,不发送通知
      allEditors.forEach(mail => {
        Drive.Permissions.create(
          {
            role: "writer",
            type: "user",
            emailAddress: mail
          },
          fichierId,
          { sendNotificationEmail: false }
        );
      });

      Logger.log("行" + (i+1) + "的文件共享完成: " + fichierUrl);
    } catch (error) {
      Logger.log("行" + (i+1) + "处理失败,URL: " + fichierUrl);
      Logger.log("错误信息: " + error.message);
    }
  }
}

关键优化点

  • 修正列索引:原问题中B/C列对应数组索引1/2,修复了原代码错误使用索引2/3的问题。
  • 空值过滤:跳过无URL的行,过滤空收件人,避免无效操作。
  • 权限去重:用Set合并收件人,防止重复添加相同权限。
  • 统一API调用:仅使用Drive.Permissions.create实现无通知添加编辑器,避免冲突。
  • 日志增强:添加行号标识,方便定位问题行。

内容的提问来源于stack exchange,提问作者Nicolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:55:09