Download a table as CSV using jQuery

Mon, 07 January 2019

tableDownload.js
(function($) {
    $.fn.tableDownload = function(file_name) {
        if (typeof file_name === 'undefined') {
            file_name = 'tableDownload.csv';
        }
        if (file_name.substr(-4, 4) !== '.csv') {
            file_name += '.csv'
        }
        var tableCellClean = function(val) {
            var s = '';
            for (var i=0;i<val.length;i++) {
                if (val[i] == '"') {
                    s += '""';
                } else {
                    s += val[i];
                }
            }
            return s;
        };
        var table_selector = this.attr('data-target');

        var trs = $('tr', $(table_selector));
        var data = [];
        for (var tri=0;tri<trs.length;tri++) {
            var ths = $('th', $(trs[tri]));
            var tds = $('td', $(trs[tri]));
            var row = [];
            for (var cith=0;cith<ths.length;cith++) {
                var thText = tableCellClean($(ths[cith]).text().trim());
                row.push('"' + thText + '"');
            }
            for (var citd=0;citd<tds.length;citd++) {
                var tdText = tableCellClean($(tds[citd]).text().trim());
                row.push('"' + tdText + '"');
            }
            data.push(row);
        }
        var csv = "data:text/csv;charset=utf-8,";
        data.forEach(function(rowArray){
            var row = rowArray.join(",");
            csv += row + "\r\n";
        });
        var encodedUri = encodeURI(csv);
        this.attr('href', encodedUri).attr('download', file_name);

        return this;
    };
}(jQuery));
Example.html
<html>
    <head>
        <script src="/path/to/jquery-3.3.1.min.js"></script>
    </head>
    <body>
        <a href="#" data-target="#my_table">Download</a>
        <table id="my_table">
            <thead>
                <tr>
                    <th>Header 1</th>
                    <th>Header 2</th>
                    <th>Header 3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Row 1, Cell 1</td>
                    <td>Row 1, Cell 2</td>
                    <td>Row 1, Cell 3</td>
                </tr>
                <tr>
                    <td>Row 2, Cell 1</td>
                    <td>Row 2, Cell 2</td>
                    <td>Row 2, Cell 3</td>
                </tr>
            </tbody>
        </table>

        <script>
            $('#download').tableDownload('my-table-data.csv');
        </script>
    </body>
</html>
my-table-data.csv
"Header 1","Header 2","Header 3"
"Row 1, Cell 1","Row 1, Cell 2","Row 1, Cell 3"
"Row 2, Cell 1","Row 2, Cell 2","Row 2, Cell 3"