Download a CSV File from Spreadsheet Using Google HTML Service

Here, I introduce how to download a CSV file from spreadsheet using Google HTML Service.

  1. Using “onOpen()", it addes menu for launching a dialog.

  1. After launching the dialog, “getFileUrl()” is launched by pushing a button. “getFileUrl()” exports a CSV file and outputs download URL.

  2. The CSV file is downloaded by “executeDownload()".

Please put both HTML and GAS to a GAS project.

HTML : download.html

<!DOCTYPE html>
<html>
  <body>
    Download CSV?
    <form>
      <input type="button" value="ok" onclick="google.script.run
                                              .withSuccessHandler(executeDownload)
                                              .getFileUrl();" />
    </form>
  </body>
  <script>
    function executeDownload(url) {
      window.location.href = url;
    }
  </script>
</html>

GAS :

function onOpen() {
  SpreadsheetApp.getUi()
                .createMenu('export')
                .addItem('export csv files', 'dialog')
                .addToUi();
}

function dialog() {
  var html = HtmlService.createHtmlOutputFromFile('download');
  SpreadsheetApp.getUi().showModalDialog(html, 'CSV download dialog');
}

function getFileUrl() {
    var filename = "#####"; // CSV file name
    var folder = "#####"; // Folder ID

    var csv = "";
    var v = SpreadsheetApp // Now spreadsheet is an active sheet.
            .getActiveSpreadsheet()
            .getActiveSheet()
            .getDataRange()
            .getValues();
    v.forEach(function(e) {
      csv += e.join(",") + "\n";
    });
    var url = DriveApp.getFolderById(folder)
              .createFile(filename, csv, MimeType.CSV)
              .getDownloadUrl()
              .replace("?e=download&gd=true","");
    return url;
}