23

I have a comma separated variable in my .js file, for example:

var out='';
out+="1,val1,val2,val3,val4\n";
out+="2,val1,val2,val3,val4\n";
out+="3,val1,val2,val3,val4\n";

I am displaying this value in a browser using document.write(out);.
I would like the out variable to be downloadable as a .csv file.

From data stored in a variable, is there any way to create a csv file and its associated download link in JavaScript?

jsFiddle

6
  • 1
    Is that syntax what you want really? All those valN strings are useless...Check jsbin.com/ifenic/1/edit Commented Jun 14, 2013 at 7:38
  • There i no way to do this. Otherwise we would be living in the world with viruses compiling directly in your browser Commented Jun 14, 2013 at 7:43
  • 1
    i have comma separated value in js file want to save this data as csv Commented Jun 14, 2013 at 7:43
  • 1
    Well, your syntax doesn't even make sense. Try building your own solution first, look on Google for documentation. When you think you've tried all possible solutions, then come back with the code that failed, post a live example and explain what didn't work. That's how Stackoverflow works; you need to show some effort first. Commented Jun 14, 2013 at 7:47
  • @ooops: I think we are living in that world. Commented Jun 14, 2013 at 8:33

2 Answers 2

52

Depends on browser support, but that's getting pretty good with new browsers: http://jsfiddle.net/3fMeL/2/

var CSV = [
    '"1","val1","val2","val3","val4"',
    '"2","val1","val2","val3","val4"',
    '"3","val1","val2","val3","val4"'
  ].join('\n');

window.URL = window.webkitURL || window.URL;

var contentType = 'text/csv';

var csvFile = new Blob([CSV], {type: contentType});

var a = document.createElement('a');
a.download = 'my.csv';
a.href = window.URL.createObjectURL(csvFile);
a.textContent = 'Download CSV';

a.dataset.downloadurl = [contentType, a.download, a.href].join(':');

document.body.appendChild(a);

So the first item is the Blob object, this creates the object that can be downloaded. https://developer.mozilla.org/en-US/docs/Web/API/Blob (http://caniuse.com/#search=blob)

The next part is the download attribute of the link, which informs the browser to download the CSV file rather than opening it in the browser window. (http://caniuse.com/#feat=download)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! is this possible without link (download csv link)?
@RSSisodiya You can create a link and fire the click event on it. You need a link to take advantage of the download attribute. If you put the URL directly in to the browser window.location.href it will just open, and not download.
-1

there is jquery plugin for output file at the client side without server side interaction,

https://github.com/dcneiner/Downloadify

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.