Skip to content

Instantly share code, notes, and snippets.

@cmbaughman
Created April 10, 2017 22:35
Show Gist options
  • Save cmbaughman/586fd115b627e0a355553015ad5f0576 to your computer and use it in GitHub Desktop.
Save cmbaughman/586fd115b627e0a355553015ad5f0576 to your computer and use it in GitHub Desktop.
JavaScript to export a CSV
// Originally found on
//https://appendto.com/2017/04/use-javascript-to-export-your-data-as-csv/
function convertArrayOfObjectsToCSV(args) {
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;
        data = args.data || null;
        if (data == null || !data.length) {
            return null;
        }
        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';
        keys = Object.keys(data[0]);
        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;
        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;
                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });
        return result;
    }
    function downloadCSV(args) {
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: args.arrayOfObjects
        });
        if (csv == null) return;
        filename = args.filename || 'export.csv';
        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);
        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment