Snippets

Piotr Szrajber Smart M.App - Triggering download of a CSV file contaning rows in the current selection

Created by Piotr Szrajber last modified
function formatCsv(rows, config) {
    config = config || {};
    // CSV delimiter
    var delim = config.delimiter || ",",
        // New Line character
        newl = config.newline || "\n",
        // By default take all original columns, dimensions and measures
        header = config.header || Object.keys(rows[0]).filter(function(key) {
            return Object.hasOwnProperty.call(rows[0], key) && typeof rows[0][key] !== "function";
        });
    // format the CSV with the header
    return [header.join(delim)].concat(rows.map(function(row) {
        return header.map(function(col) {
            return row[col];
        }).join(delim);
    })).join(newl);
}

function triggerDownload(content, config) {
    config = config || {};
    var filename = config.filename || "test.csv",
        mimetype = config.mime || "text/csv",
        charset = config.charset || "utf-8";

    //CSV will be downloaded immediately but this can be invoked in any event
    var encodedUri = "data:" + mimetype + ";charset=" + charset + "," + encodeURI(content);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();
}

gsp.ready("v1.0", function(gsp) { // TODO: remove in Studio
        gsp.bi.stage.findSelectedRecords({
                //layer: "labor_geom"
            }, function(ret) { // ["id1", "id2", ..., "idn"]
                // do something with ret
                var csv = formatCsv(ret, {
                // delimiter: ","
                // newline: "\n",
                // header: ["id_woj", "YEAR", "POPULATION_TOTAL", "WAGES_TOTAL_REAL"]
                });
                triggerDownload(csv, {
                // filename: "test.csv"
                // mime: "text/csv"
                // charset: "utf-8"
                });
            },
            function(err) {
                // display err
                console.error(err)
            });
    }) // TODO: remove in Studio

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.