Google Apps Script:谷歌表格转PDF存共享云端失败求助
原代码问题分析
- 报错
GoogleJsonResponseException: API call to drive.files.copy failed with error: Required:因为Drive.Files.copy的第二个参数传入了Sheet对象,而该方法需要的是Spreadsheet的文件ID,不是Sheet对象。 - 代码逻辑错误:原代码是复制原表格文件,而非生成并保存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:
- 打开脚本编辑器 → 点击「扩展」→「应用脚本」
- 点击左侧「服务」→「添加服务」→ 选择「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
相关产品推荐
相关产品推荐

