Export CSV File from Spreadsheet and Make Download Button

This is a script to export a CSV file from spreadsheet and make an user download it. When the users download it, they can download by push a button made by this script.

In order to use this script, put both HTML and script in a GAS project.

html :

This file name is “download.html”.

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

Script :

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

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

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

    var csv = "";
    var v = SpreadsheetApp
            .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;
}

Process :

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

  2. After launching the dialog, “saveAsCSV()” is launched by pushing a button. “saveAsCSV()” exports a CSV file and outputs download URL. At current script, all of data on active sheet is retrieved and exported CSV. If you want to retrieve a range you need, please use “getRange()”.

  3. The CSV file is downloaded by “executeDownload()”.

You can set csv file-name and output folder by “filename” and “folder”, respectively. In this sample, the source sheet is the sheet which opens currently. If you want to other sheet, please change this script.

 Share!