9

I'm trying to download a specific *.csv file from my Google Drive to a local folder on my computer. I have tried the following with no luck:

ContentService.createTextOutput().downloadAsFile(fileName);

I don't get an error, and nothing appears to happen. Any ideas on what's wrong with my attempt?

Rubén
  • 34,714
  • 9
  • 70
  • 166
Jason Griffin
  • 91
  • 1
  • 1
  • 2

1 Answers1

7

ContentService is used to serve up text content as a Web Application. The line of code you've shown does nothing on it's own. Assuming that it's a one-line body of a doGet() function that you've deployed as a Web App, then here's why you're seeing nothing:

Since we have no content, there's nothing to download, so you see, well, nothing.

CSV Downloader Script

This script will get the text content of a csv file on your Google Drive, and serve it for downloading. Once you've saved a version of the script and published it as a web app, you can direct a browser to the published URL to start a download.

Depending on your browser settings, you may be able to select a specific local folder and/or change the file name. You have no control over that from the server side, where this script runs.

/**
 * 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
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
  • Hi, thanks for you answer. I can download the file manually using the browser.But do you know how can I download it use a bash script? – zhihong Aug 21 '14 at 14:29
  • @zhihong - check out `curl`. Lots of examples here in SO. – Mogsdad Aug 22 '14 at 03:20
  • thanks for your quick suggestion. As in the browser you already be authenticated, but if I use curl, I got "Unauthorized" feedback. I today found google also have the spreadsheet API, think maybe that is the correct one I should use. – zhihong Aug 22 '14 at 11:44