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

Google Apps Script:谷歌表格转PDF存共享云端失败求助

解决Google表格导出PDF至Shared Drive的问题

原代码问题分析

  1. 报错GoogleJsonResponseException: API call to drive.files.copy failed with error: Required:因为Drive.Files.copy的第二个参数传入了Sheet对象,而该方法需要的是Spreadsheet的文件ID,不是Sheet对象。
  2. 代码逻辑错误:原代码是复制原表格文件,而非生成并保存PDF。

正确实现方案

方案1:使用DriveApp(简单直接,需编辑权限)

直接生成PDF Blob,然后在Shared Drive的目标文件夹中创建文件,注意使用文件夹ID而非名称(Shared Drive中同名文件夹可能存在,且DriveApp通过名称查找不稳定)。

function savePDFToSharedDrive() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const targetFolderId = "替换为你的Shared Drive目标文件夹ID";
  const activeSheet = ss.getActiveSheet();
  // 生成PDF文件名(和原逻辑一致)
  const fileName = "test_" + activeSheet.getRange('B3').getValue().toString() + ".pdf";

  // 生成PDF格式的Blob
  const pdfBlob = ss.getBlob().getAs('application/pdf').setName(fileName);

  // 获取目标文件夹并创建PDF文件
  const targetFolder = DriveApp.getFolderById(targetFolderId);
  targetFolder.createFile(pdfBlob);
}

方案2:使用Drive API(更稳定支持Shared Drive)

如果DriveApp方法出现权限问题,可使用Drive API实现,需先启用Drive API:

  1. 打开脚本编辑器 → 点击「扩展」→「应用脚本」
  2. 点击左侧「服务」→「添加服务」→ 选择「Google Drive API」并添加
function savePDFToSharedDriveWithAPI() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const targetFolderId = "替换为你的Shared Drive目标文件夹ID";
  const activeSheet = ss.getActiveSheet();
  const fileName = "test_" + activeSheet.getRange('B3').getValue().toString() + ".pdf";

  // 生成PDF Blob
  const pdfBlob = ss.getBlob().getAs('application/pdf');

  // 调用Drive API上传PDF到Shared Drive
  Drive.Files.create(
    {
      name: fileName,
      parents: [{ id: targetFolderId }],
      mimeType: 'application/pdf'
    },
    pdfBlob,
    { supportsAllDrives: true } // 必须开启此参数支持Shared Drive
  );
}

注意事项

  • 确保你对目标Shared Drive文件夹拥有编辑权限,否则会触发权限错误。
  • 优先使用文件夹ID而非名称,避免查找失败。
  • 使用Drive API时,必须先在脚本服务中启用Google Drive API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:45:11