错误异常:访问带有 id 的文档时服务电子表格失败

时间:2021-02-26 18:00:30

标签: google-apps-script google-sheets-api spreadsheet document

我在之前的答案中找不到此错误的解决方案。我在 Google Apps Scripts with Google Sheets 下运行这个脚本。因此,我希望您查看我的简单代码行,看看是否有我忽略的内容:

var firstCSV = SpreadsheetApp.openByUrl("https://drive.google.com/file/d/14EA51XsRpohpFVCwpO3sZwf_H3o6Dp_o/edit#gid=0");

此行出错 -

Exception: Service Spreadsheets failed while accessing document with id 14EA51XsRpohpFVCwpO3sZwf_H3o6Dp_o. GregReport @ Receipts Calculator.gs:37

  • 我首先尝试仅使用 ID 号使用“openById”并得到 同样的错误信息。

  • 接下来我尝试使用文档的 URL 使用“openByUrl”并得到
    同样的错误信息。

  • 我检查了 Google Drive 上的文件,它在那里,我可以打开它。

  • 我自己在脚本中运行了这行代码并得到了同样的错误。

  • 我将代码中的 URL 更改为 Sheets 文档 URL,然后我得到了
    同样的错误。

  • 原始文件的扩展名为 .csv,但我的理解是这样的
    在表格中应该可以正常工作。

  • 通过两种文档格式和不同的方法,我得到了这个
    同样的错误。

  • 我不知道的任何建议或代码更新将不胜感激。 我要做的就是打开一个电子表格并从中提取一些数据 它使用表格中内置的脚本。

1 个答案:

答案 0 :(得分:0)

遗憾的是,无论是使用文件 ID 还是驱动器 URL,都无法在 Apps 脚本中直接调用 CSV 文件作为电子表格。

您需要做的是解析 CSV 并获取其内容并将其粘贴到 Apps 脚本中的电子表格中。请参阅下面的示例代码:

function myFunction() {
  var file = DriveApp.getFilesByName(your-filename-here).next();
  var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1,1,csvData.length, csvData[0].length).setValues(csvData)
}
相关问题