Creating a CSV file on the fly and downloading it using Javascript

There might be situations where you need to create a CSV using some data available within JS layer and allow a user to download it. So you need to construct the CSV file on the fly and then allow the user to download the file.

Data-URI scheme helps in achieving this. You can specify the contents and file name of the file to be downloaded and attach these properties to an anchor element.

This is how you can do it:


<html>

<script type='text/JavaScript'>

 function downloadAsCSV() {
    var a = document.createElement('a');
    a.href = 'data:attachment/csv,' + encodeURIComponent("hello,world!\r\nHow,are,you?");
    a.target = '_blank';
    a.download = 'sample.csv';
    document.body.appendChild(a);
    a.click();
 }

</script>

<body>
 <span style="cursor:pointer;" onclick="downloadAsCSV()">Download as CSV</span>
</body>

</html>

This works on Chrome and Firefox.

35.0.1916.99 version of Chrome has a bug, which can be tracked here.