You need to enable JavaScript to run this app. Google Apps Script发票PDF功能同事执行时报文档访问权限不足错误
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script发票PDF功能同事执行时报文档访问权限不足错误

问题场景
  • 团队基于Google Sheets开发发票自动化功能,同事手动录入数据后点击「发送」按钮即可完成三项操作:
    • 关联「发票模板」工作表,通过Apps Script将模板内容生成PDF
    • 通过同事个人Gmail账号将生成的PDF发送给对应收件人
    • 将生成的PDF自动存储到Google Drive指定文件夹
  • 脚本初始在开发者个人账号下可全流程正常运行,同事触发时弹出报错:Exception: You do not have permission to access the requested document. at emailInvoiceAsPDF(Invoice:10:29)
  • 当前部署的原始完整脚本如下(所有代码、技术参数、链接保持原样):
/**
   * @NotOnlyCurrentDoc
   */

function emailInvoiceAsPDF() {
  DocumentApp.getActiveDocument();
  DriveApp.getFiles();
 /**
   * @NotOnlyCurrentDoc
   */
  // This is the link to my spreadsheet with the Form responses and the Invoice Template sheets
  // Add the link to your spreadsheet here 
  // or you can just replace the text in the link between "d/" and "/edit"
  const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1pzKLOSnKt2NNCOL8-mG1YVgELp8Hf-v9PhMkSI-YYte/edit");

  // We are going to get the email address from the cell "B7" from the "Invoice" sheet
  // Change the reference of the cell or the name of the sheet if it is different
  const value = ss.getSheetByName("Invoice Template").getRange("J32").getValue();
  const email = value.toString();

  var sheet1=ss.getSheetByName('Invoice template');
  var subject = sheet1.getRange("B2:N2").getValue();

  // Subject of the email message


  // Email Text. You can add HTML code here - see ctrlq.org/html-mail
  const body = "Dear customer,<br><br> Please find the attached Invoice. <br><br> Thank You.";

  // Again, the URL to your spreadsheet but now with "/export" at the end
  // Change it to the link of your spreadsheet, but leave the "/export"
  const url = 'https://docs.google.com/spreadsheets/d/1pzSZZSnKtPPieRL8-mG1YVgELp7Jv-v9PhMkSI-AeZA/export?';

  const exportOptions =
    'exportFormat=pdf&format=pdf' + // export as pdf
    '&size=letter' + // paper size letter / You can use A4 or legal
    '&portrait=true' + // orientation portal, use false for landscape
    '&scale=4' +
    '&sheetnames=false&printtitle=false' + // hide optional headers and footers
    '&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
    '&fzr=false' + // do not repeat row headers (frozen rows) on each page
    '&gid=196383625'; // the sheet's Id. Change it to your sheet ID.
  // You can find the sheet ID in the link bar. 
  // Select the sheet that you want to print and check the link,
  // the gid number of the sheet is on the end of your link.
  
  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  
  // Generate the PDF file
  var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
  
  // Send the PDF file as an attachement 
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments: [{
            fileName: "Invoice" + ".pdf",
            content: response.getBytes(),
            mimeType: "application/pdf"
        }]
    });

   // Save the PDF to Drive. The name of the PDF is going to be the name of the Company (cell B5)
   const nameFile = ss.getSheetByName("Invoice Template").getRange("B2").getValue().toString() +".pdf"
   var Folder = DriveApp.getFolderById("12oHonHMo0ZBS-qZkxe1Iuyfm5miy0fXQ");
  Folder.createFile(response.setName(nameFile))
}
报错根因定位
  • 跨表格硬编码权限错配:脚本第10行执行SpreadsheetApp.openByUrl时,访问的是开发者个人私有表格;同时导出PDF的URL指向了另一个ID完全不同的私有表格。同事触发脚本时使用的是自身的OAuth授权,未被授予这两个私有表格的访问权限,直接触发权限拒绝报错,和报错堆栈定位的行号完全匹配。
  • Drive目标文件夹权限缺失:脚本内硬编码的目标存储文件夹为开发者个人私有文件夹,未对使用功能的同事开放编辑权限,就算PDF生成环节跑通,文件归档步骤也会触发同类权限报错。
  • 冗余无效代码触发额外权限校验:脚本开头调用的DocumentApp.getActiveDocument()属于Google Docs环境API,在Sheets脚本运行环境中无对应激活对象,会触发额外的文档访问权限校验要求,放大权限不匹配的问题。
  • 工作表名称大小写不统一:脚本内先后使用Invoice Template、Invoice template两种写法,和实际工作表名称不匹配时会触发空值引用类错误。
修复操作步骤
  • 移除硬编码的跨表格访问逻辑:将原来写死URL的openByUrl调用替换为const ss = SpreadsheetApp.getActiveSpreadsheet(),直接获取脚本绑定的当前打开的表格,从根源上避免跨账号跨表格的访问权限问题。
  • 统一导出PDF的URL中的表格ID,确保和当前使用的表格ID完全一致,不要保留两个不同的硬编码表格ID。
  • 调整目标Drive文件夹的共享权限:给所有需要使用功能的同事开放该文件夹的编辑权限,或设置为同组织域内可编辑,确保同事账号可以在文件夹内创建文件。
  • 删除冗余无效代码:移除脚本中重复的@NotOnlyCurrentDoc注释、无意义的DocumentApp.getActiveDocument()调用,减少不必要的OAuth权限申请项。
  • 统一脚本内所有工作表名称的大小写,和实际表格内的工作表命名完全对齐,避免因大小写差异找不到目标工作表的问题。
  • 重新部署脚本时设置执行身份为「触发脚本的用户」,确保所有操作(访问表格、生成PDF、发送Gmail邮件、写入Drive文件)都使用同事自身的账号权限执行,匹配预设的「使用同事个人Gmail发送邮件」的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 17:57:07