从Google Apps Script将文件从Google Drive下载到本地文件夹

9

我试图从Google Drive下载一个特定的*.csv文件到我的电脑本地文件夹。我尝试了以下方法,但都没有成功:

ContentService.createTextOutput().downloadAsFile(fileName);

我没有收到任何错误提示,也没有任何显示。您认为我的尝试存在什么问题吗?
1个回答

7
ContentService用于作为Web应用程序提供文本内容。您展示的代码行本身不起作用。假设它是一个doGet()函数的一行主体,您已将其部署为Web应用程序,那么您看不到任何内容的原因如下:

由于我们没有内容,所以没有什么可以下载的,因此您看到了,呃,没什么

CSV下载器脚本

此脚本将获取Google Drive上csv文件的文本内容,并将其提供下载。保存脚本版本并将其发布为Web应用程序后,您可以将浏览器定向到发布的URL以开始下载。

根据您的浏览器设置,您可以选择特定的本地文件夹和/或更改文件名。从运行此脚本的服务器端,您无法控制它。

/**
 * This function serves content for a script deployed as a web app.
 * See https://developers.google.com/apps-script/execution_web_apps
 */
function doGet() {
  var fileName = "test.csv"
  return ContentService
            .createTextOutput()            // Create textOutput Object
            .append(getCsvFile(fileName))  // Append the text from our csv file
            .downloadAsFile(fileName);     // Have browser download, rather than display
}    

/**
 * Return the text contained in the given csv file.
 */
function getCsvFile(fileName) {
  var files = DocsList.getFiles();
  var csvFile = "No Content";

  for (var i = 0; i < files.length; i++) {
    if (files[i].getName() == fileName) {
      csvFile = files[i].getContentAsString();
      break;
    }
  }
  return csvFile
}

嗨,谢谢你的回答。我可以使用浏览器手动下载文件。但是你知道如何使用bash脚本下载它吗? - zhihong
@zhihong - 请查看 curl。这里有很多示例在 Stack Overflow 上。 - Mogsdad
感谢您的快速建议。在浏览器中,您已经通过身份验证,但如果我使用curl,则会收到“未经授权”的反馈。今天我发现Google也有电子表格API,认为那可能是我应该使用的正确API。 - zhihong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接