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>
    Download CSV?
      <input type="button" value="ok" onclick="google.script.run
                                              .saveAsCSV();" />
    function executeDownload(url) {
      window.location.href = url;

Script :

function onOpen() {
                .addItem('export as csv files', 'dialog')

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
    v.forEach(function(e) {
      csv += e.join(",") + "\n";
    var url = DriveApp.getFolderById(folder)
              .createFile(filename, csv, MimeType.CSV)
    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.