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

如何修改Google Apps Script代码实现复制Google Doc时保留原有共享人员

Google Doc模板复制同步共享权限解决方案

你现有的代码仅实现了模板内容复制和内容占位符替换,默认不会同步原模板的共享权限,我们在原有代码基础上新增了权限同步逻辑,你直接删除现有全部代码,替换为下方完整代码即可使用,所有原有功能不受影响,生成的新文档会和原模板共享给完全相同的人员,和手动复制的效果一致。

function onOpen() {
  const ui = SpreadsheetApp.getUi();
  const menu = ui.createMenu('Create My Checklist');
  menu.addItem('New Checklist', 'createNewGoogleDocs')
  menu.addToUi();
}
function createNewGoogleDocs() {
  //模板文档的ID
  const googleDocTemplate = DriveApp.getFileById('1qRQ07PDmz1il9IftM9GIJfY37vTusfQZhhNS1BRELJQ');
  
  //生成文档存储的目标文件夹ID
  const destinationFolder = DriveApp.getFolderById('1JufckhwXlAXDAE3_-f60lHQQ-jqe9Mx1')
  //获取数据表格对象
  const sheet = SpreadsheetApp
    .getActiveSpreadsheet()
    .getSheetByName('Data')
  
  //读取表格所有数据为二维数组
  const rows = sheet.getDataRange().getValues();
  
  //遍历处理每一行数据
  rows.forEach(function(row, index){
    //跳过表头行
    if (index === 0) return;
    //跳过已经生成过文档的行(文档链接列已有内容)
    if (row[10]) return;
    //在目标文件夹中生成模板副本,按规则命名
    const copy = googleDocTemplate.makeCopy("My Checklist - " + row[2] + " - " + row[4] + " - " +  row[5], destinationFolder)
    
    // 新增:同步原模板的所有共享权限到新文档
    const editors = googleDocTemplate.getEditors();
    editors.forEach(editor => copy.addEditor(editor.getEmail()));
    const viewers = googleDocTemplate.getViewers();
    viewers.forEach(viewer => copy.addViewer(viewer.getEmail()));

    //打开新生成的文档
    const doc = DocumentApp.openById(copy.getId())
    //获取文档正文对象
    const body = doc.getBody();
    
    //替换正文中的占位符为表格对应行的内容
    body.replaceText('{{Employee ID}}', row[1]);
    body.replaceText('{{Name}}', row[2]);
    body.replaceText('{{Level}}', row[3]);
    body.replaceText('{{Department}}', row[4]);
    body.replaceText('{{Business Unit}}', row[5]);
    body.replaceText('{{Location}}', row[6]);
    
    //保存并关闭文档
    doc.saveAndClose();
    //获取新文档的链接
    const url = doc.getUrl();
    //将链接写入表格的文档链接列
    sheet.getRange(index + 1, 11).setValue(url)
    
  })
}

注意事项

  • 首次运行代码时会触发权限申请,按照页面指引完成授权即可正常使用
  • 你需要持有模板文件的管理权限,否则无法读取模板的共享人员列表,导致权限同步失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:24:02