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

如何保护工作表并设置与另一个受保护工作表相同的编辑者

解决复制工作表后保护设置不生效的问题

问题根源

你的代码存在两个关键问题:

  • 获取模板保护的方式错误:调用templateSheet.protect()会尝试创建新保护,而非读取模板已有的整表保护,导致获取的编辑器列表不符合模板实际设置。
  • 用户对象判断失效:User是引用类型,即使是同一个用户,不同实例用includes()判断会返回false,导致所有编辑器被错误标记为需要移除,最终保护规则未按预期生效。
    另外,新创建的保护默认可能开启域内用户编辑权限,这也会导致所有有表格访问权的用户都能编辑新表。

修复后的代码

function setProtection(templateSheet, newSheet) {
  // 获取模板已有的整表保护
  const templateProtections = templateSheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
  if (templateProtections.length === 0) {
    Logger.log("模板工作表无整表保护,跳过设置");
    return;
  }
  const templateProtection = templateProtections[0];
  
  // 创建新表的整表保护
  const newProtection = newSheet.protect();
  
  // 同步保护描述(可选,和模板保持一致)
  newProtection.setDescription(templateProtection.getDescription());
  
  // 移除新保护的所有默认编辑器(所有者无法被移除,会自动保留)
  newProtection.removeEditors(newProtection.getEditors());
  
  // 添加模板允许的编辑器列表
  const templateEditors = templateProtection.getEditors();
  if (templateEditors.length > 0) {
    newProtection.addEditors(templateEditors);
  }
  
  // 同步模板的域编辑权限设置
  newProtection.setDomainEdit(templateProtection.isDomainEditAllowed());
  
  Logger.log("新表保护设置完成,允许编辑的用户:" + templateEditors);
}

关键说明

  • 获取现有保护:用getProtections(SpreadsheetApp.ProtectionType.SHEET)获取模板已有的整表保护,避免创建新保护覆盖原有设置。
  • 重置编辑器列表:先移除新保护的所有默认编辑器,再添加模板的允许用户,确保权限完全同步。
  • 同步域权限:setDomainEdit()确保新表和模板在域内用户编辑权限上保持一致,避免默认开启导致的权限泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:05:17