6

I've created a file in Google Apps Script as follows

DocsList.createFile(
   "test.csv", 
   "Row1Col1,Row1Col2 \r\n Row2Col1,RowCol2 \r\n Row3Col1,Row3Col2");

How to download it programmatically (via a popup Download dialog for example) ?

Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82

3 Answers3

4

Try using ContentService, you can trigger a download and even set the file name via the TextOutput.downloadAsFile method. You can also set the content mime type of the returned data, though only to a predefined enum constant. See their examples.

DDD
  • 1,462
  • 15
  • 19
  • Thanks, but whenever I try the code provided in JsonP sample, i got the following error: "Uncaught SyntaxError: Unexpected token < ", any idea how to test it ? – Ashraf Bashir Dec 26 '12 at 12:52
  • I added a new thread for the issue which exists in my last comment, if you can give a hand in this issue too, it will be great ! You may find it in the following link: http://stackoverflow.com/questions/14041124/jsonp-with-google-apps-script, Thanks :) – Ashraf Bashir Dec 26 '12 at 13:23
4

To download a file with apps script you need to either publish the app, and use the doGet() method (otherwise the "downloadFileAs" won't work)

OR...

create the file in Drive, and provide a link in a dialog ui. here are two options for links, one requires users to be logged in the other doesn't taken from here

  var dat=getFileDataFromAnotherFunction();
  var file = DriveApp.createFile('name.csv',dat);
  var t = HtmlService.createTemplateFromFile('DownloadDialog');
  t.url1 = getDlUrl(file);
  t.url2 = file.getDownloadUrl().replace('&gd=true','') 
  rt =  t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
  uia.showModalDialog(rt,'Download the csv')

where "DownloadDialog.html"

is the following file (also in the script editor )

<div>
<a target="_blank" href="<?= url1 ?>">  l1 </a>
<br>
<hr>
<a target="_blank" href="<?= url2 ?>"> link 2 </a> 
</div>
Community
  • 1
  • 1
vish
  • 1,046
  • 9
  • 26
3

If you want to show a download dialog at client end then following code works. It is an example for CSV file.

return ContentService.createTextOutput("bbb,aaa,ccc").downloadAsFile("MyData.csv")
    .setMimeType(ContentService.MimeType.CSV);
Hari Das
  • 10,145
  • 7
  • 62
  • 59
  • 1
    Not working for me in Chrome 55.0.2883.95 (64-bit). I created an Apps Script attached to a spreadsheet that contained the above within a function. When I try to Run the function, I see "Preparing to execute" followed by "Running function ...". No SaveAs dialog appears and no file is written. What else is needed to make it work? – Mike Ellis Jan 23 '17 at 15:14