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?
Create a blob with the csv data .ie
var blob = new Blob([data], type:"text/csv");
If the browser supports saving of blobs i.e
if window.navigator.mSaveOrOpenBlob)===true
, then save the csv data using:window.navigator.msSaveBlob(blob, 'filename.csv')
If the browser doesn't support saving and opening of blobs, then save csv data as:
Full Code snippet:
I would recommend using a library like PapaParse: https://github.com/mholt/PapaParse
The accepted answer currently has multiple issues including:
One arrow function with ES6 :
Then :
In case anyone needs this for reactjs,
react-csv
is there for thatThere are two questions here:
All the answers to the first question (except the one by Milimetric) here seem like an overkill. And the one by Milimetric does not cover altrenative requirements, like surrounding strings with quotes or converting arrays of objects.
Here are my takes on this:
For a simple csv one map() and a join() are enough:
This method also allows you to specify column separator other than a comma in the inner join. for example a tab:
d.join('\t')
On the other hand if you want to do it properly and enclose strings in quotes "", then you can use some JSON magic:
if you have array of objects like :
The answers above work, but keep in mind that if you are opening up in the .xls format, columns ~~might~~ be separated by
'\t'
instead of','
, the answer https://stackoverflow.com/a/14966131/6169225 worked well for me, so long as I used.join('\t')
on the arrays instead of.join(',')
.In Chrome 35 update, download attribute behavior was changed.
https://code.google.com/p/chromium/issues/detail?id=373182
to work this in chrome, use this