I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8
and have all the attribute info in array, which looks like this:
[["name1", "city_name1", ...]["name2", "city_name2", ...]]
Any idea how I can export this to CSV
on the client side?
I added to Xavier Johns function to also include the field headers if needed, uses jQuery though. The $.each bit will need changing for a native javascript loop
This is a modified answer based on the accepted answer wherein the data would be coming from JSON.
I use this function to convert an
string[][]
to a csv file. It quotes a cell, if it contains a"
, a,
or other whitespace (except blanks):Note: does not work on Internet Explorer < 11 unless
map
is polyfilled.Note: If the cells contain numbers, you can add
cell=''+cell
beforeif (cell.replace...
to convert numbers to strings.Or you can write it in one line using ES6:
There you go :
In case anyone needs this for knockout js, it works ok with basically the proposed solution:
html:
view model:
You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):
Then you can use JavaScript's
window.open
andencodeURI
functions to download the CSV file like so:Edit:
If you want to give your file a specific name, you have to do things a little differently since this is not supported accessing a data URI using thewindow.open
method. In order to achieve this, you can create a hidden<a>
DOM node and set itsdownload
attribute as follows: