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 | var ieOldFn = null; |
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.