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

时间:2013-06-29 02:27:29

标签: download google-apps-script google-drive-api

我正在尝试从我的Google云端硬盘下载特定的*.csv文件到我计算机上的本地文件夹。我试过以下没有运气:

ContentService.createTextOutput().downloadAsFile(fileName);

我没有收到错误,似乎什么也没发生。关于我的尝试有什么问题的任何想法?

1 个答案:

答案 0 :(得分:3)

ContentService用于将文本内容作为Web应用程序提供。你展示的代码行没有任何关系。假设它是你作为Web应用程序部署的doGet()函数的单行体,那么这就是你什么都看不见的原因:

由于我们没有内容,因此无需下载,因此您可以看到没有

CSV下载程序脚本

此脚本将在您的Google云端硬盘上获取csv文件的文本内容,并将其提供给下载。保存脚本版本并将其作为Web应用程序发布后,您可以将浏览器定向到已发布的U​​RL以开始下载。

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

/**
 * 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
}