JS Array to CSV Download

Recently I was tasked with generating a CSV file using the data from a table. Normally I would do this in php where the actual data was coming from, but I didn’t see the need to go hacking around on the back-end when this could be done in JS after all the data was loaded. The data was loaded via AJAX, so it took a bit to populate.

The table also uses DataTables to make it pretty, sortable, and paged, but since it was paged I couldn’t just grab the data from the <td>’s. So instead I made an array, then pushed the ‘row’ data to it inside the ajax call. Once all the data is in, the download button appears and you get a CSV file.

Note: This is mostly pulled from a gist example, link is commented in the snippet below.

var csv_arr = [];
// add header first before pushing data
csv.push(["Bruh", "Data", "Date", "Ect"]);

// push some data, I did this inside the ajax call
// mentioned in the copy above
for(var i = 0; i <= somedata.length; i++){
    csv_arr.push(somedata[i]);
}

// found: https://gist.github.com/yangshun/01b81762e8d30f0d7f8f
document.querySelector("#muh_epic_button").addEventListener("click", function (){
    var csvString = csv_arr.join('\r\n'); // Windows newline
    var a = document.createElement('a');
    a.href = 'data:attachment/csv,' + csvString;
    a.target = '_blank';
    a.download = 'data.csv';
    document.body.appendChild(a);
    a.click();
});

GitHub Link