Generating a csv file on client side with Javascript

A simple way to generate or create a CSV file using only JavaScript code, without the help of any web service or server side code, is with a JavaScript Blob Object

The Blob object represents a byte sequence similar to a file and provides methods and properties to create or manipulate ranges of binary data. A blob can be created either using the constructor as shown here, or as a return value of the slice method.

With this simple code you are able to generate a CSV file with JavaScript and allow the user to download the generated file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var ieOldFn = null;
var fileName = 'peopleCsvFile.csv';
window.URL = window.URL || window.webkitURL;
var blobObj = new Blob(['Id,Name\n1,Desiree\n2,Nell\n3,Jacob\n4,Paula\n5,Rowan']);
var lnkElement = document.getElementById('lnkFile');

if (typeof window.navigator.msSaveOrOpenBlob != "undefined") { //Internet Explorer
var clickFn = function() {
window.navigator.msSaveOrOpenBlob(blobObj, fileName);
};
if(ieOldFn !== null){
//To avoid repetitions, the previous click event handler is removed
lnkElement.removeEventListener('click', ieOldFn, true);
}
lnkElement.addEventListener('click', clickFn, true);
ieOldFn = clickFn;
} else {
var fileUrl = window.URL.createObjectURL(blobObj);
lnkElement.setAttribute('href', fileUrl);
lnkElement.setAttribute('download', fileName);
}

First thing is to create a blob object whose parameter is an array containing the desired file content and then handle the download action.

If the browser is Internet Explorer, the click event of the Download Hyperlink must be handled with a proper function event handler and within the function use the msSaveOrOpenBlob method, whereas with the rest of the browsers it is enough just to set the href attribute of the hyperlink with the file url generated by the createObjectUrl method.

It is important that the anchor tag for the download link has the download attribute with the name of the file. This applies for all browsers except Internet Explorer, in which the name of the file is specified within the click event handler.

1
<a href="#" id="lnkFile" download="CsvFile.csv">Download CSV file</a>

Below is a simple demo where add as many people as you want and generate a CSV file from the list of People.

Give it a try!


PLEASE NOTE

This is only compatible with modern browsers and this still is an experimental technology. It might change in the future.


And that’s it!

Hope you like it and find it useful.

Share
© 2020 js 231 sp All Rights Reserved.
Theme by hiero