JavaScript in browser download of array in CSV format
Thu, 15 February 2018
function.js
function csvArrayDownload(data, name) { /** * Download a CSV file, in browser for the data provided. * * [ * [ * 'Column 1 title', 'Column 2 title' * ], * [ * 'value_2_a', 'value_2_b' * ], * [ * 'value_3_a', 'value_3_b' * ], * * ] * * @param {array} data * @param {string} name */ var csv = "data:text/csv;charset=utf-8,"; data.forEach(function(rowArray){ var row = rowArray.join(","); csv += row + "\\\\\\\\r\\\\\\\\n"; }); var encodedUri = encodeURI(csv); var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", name); document.body.appendChild(link); link.click(); }
usage.html
<script> csvArrayDownload( [ ["name", "age"], ["Joe", "21"], ["Jane", "18"] ], "my-file.csv" ) </script>