UrlFetch 从电子表格中获取 404 错误 URL

UrlFetch getting 404 error from spreadsheet URL

当我使用 UrlFetchApp 将传播sheet 导出为 PDF 时,我一直收到 404 - 未找到请求的实体 响应。如果我将相同的 URL 放入浏览器,PDF 下载将正确启动。

我该怎么做才能让这个示例脚本正常工作?

这里有一个 PDF 导出示例 URL,用于简单的共享(只读)传播sheet:https://docs.google.com/spreadsheets/d/133KPZyxAATG3AAY9iCSFWabefyFvQnENkHh0dyqh7MI/export?exportFormat=pdf&format=pdf&gid=0&size=letter&portrait=true&fitw=true&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&fzr=false

如果您在浏览器中单击 URL,它会获取一个 PDF Blob,这通常会启动浏览器的文件下载对话框。 (这是一个 public sheet,但在生产中 sheet 是私有的。)

function notFunctioning() {
  var options = {
    headers: {
      Authorization:"Bearer "+ScriptApp.getOAuthToken()
    },
    muteHttpExceptions : true        /// Get failure results
  }

  url = "https://docs.google.com/spreadsheets/d/133KPZyxAATG3AAY9iCSFWabefyFvQnENkHh0dyqh7MI/export?exportFormat=pdf&format=pdf&gid=0&size=letter&portrait=true&fitw=true&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&fzr=false";
  var response = UrlFetchApp.fetch(url, options);
  
  var status = response.getResponseCode();
  var result = response.getContentText();  
  debugger; // status:404  8'(
}

结果字符串内容为:

Sorry, the file you have requested does not exist.

Make sure that you have the correct URL and that the owner of the file hasn't deleted it.

当然,文件确实存在,等等。我假设我错过了一些身份验证或授权步骤。请注意,此代码与 Convert all sheets to PDF with Google Apps Script 中的代码基本相同,后者在 曾几何时...

调查:

虽然此技术不直接使用高级驱动服务,但脚本访问您的 这些权限 Google 通过 URL 驱动文件。

A note on Issue 3579: Converting spreadsheet as PDF fails with new Sheets 提供提示:

Keep in mind that solution only works if Drive or DriveApp appears somewhere in the script, so that the Drive OAuth scopes are requested and can be passed along. Check to ensure this is true for all scripts.

添加一个包含 DriveApp 函数调用的虚拟函数就足够了:

/**
 * Dummy function for API authorization only.
 */
function forAuth_() {
  DriveApp.getFileById("Just for authorization"); // https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579#c36
}

然后启用 Advanced Drive Service through "Resources > Advanced Drive Services...", and the developer console. (See this 以获取更多信息。)


就我而言,我有一个脚本一直在运行,然后停止了。我相信当我最初编写脚本时,我曾尝试使用高级驱动服务导出链接(which don't work,顺便说一句),所以我一直在启用该服务。但最近,由于其他更改,我不得不重新授权脚本,我认为同时删除了对 Drive 的授权。