Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download created csv file using Google Apps Script?

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) ?

like image 273
Ashraf Bashir Avatar asked Dec 24 '12 12:12

Ashraf Bashir


3 Answers

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.

like image 154
DDD Avatar answered Oct 31 '22 06:10

DDD


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>
like image 42
vish Avatar answered Oct 31 '22 08:10

vish


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);
like image 24
Hari Das Avatar answered Oct 31 '22 08:10

Hari Das