Export to csv in jQuery Export to csv in jQuery javascript javascript

Export to csv in jQuery


You can do that in the client side only, in browser that accept Data URIs:

data:application/csv;charset=utf-8,content_encoded_as_url

In your example the Data URI must be:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333

You can call this URI by:

  • using window.open
  • or setting the window.location
  • or by the href of an anchor
  • by adding the download attribute it will work in chrome, still have to test in IE.

To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:

<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>

To create the content, getting the values from the table, you can use table2CSV and do:

var data = $table.table2CSV({delivery:'value'});$('<a></a>')    .attr('id','downloadFile')    .attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(data))    .attr('download','filename.csv')    .appendTo('body');$('#downloadFile').ready(function() {    $('#downloadFile').get(0).click();});

Most, if not all, versions of IE don't support navigation to a data link, so a hack must be implemented, often with an iframe. Using an iFrame combined with document.execCommand('SaveAs'..), you can get similar behavior on most currently used versions of IE.


This is my implementation (based in: https://gist.github.com/3782074):

Usage: HTML:

<table class="download">...</table><a href="" download="name.csv">DOWNLOAD CSV</a>

JS:

$("a[download]").click(function(){    $("table.download").toCSV(this);    });

Code:

jQuery.fn.toCSV = function(link) {  var $link = $(link);  var data = $(this).first(); //Only one table  var csvData = [];  var tmpArr = [];  var tmpStr = '';  data.find("tr").each(function() {      if($(this).find("th").length) {          $(this).find("th").each(function() {            tmpStr = $(this).text().replace(/"/g, '""');            tmpArr.push('"' + tmpStr + '"');          });          csvData.push(tmpArr);      } else {          tmpArr = [];             $(this).find("td").each(function() {                  if($(this).text().match(/^-{0,1}\d*\.{0,1}\d+$/)) {                      tmpArr.push(parseFloat($(this).text()));                  } else {                      tmpStr = $(this).text().replace(/"/g, '""');                      tmpArr.push('"' + tmpStr + '"');                  }             });          csvData.push(tmpArr.join(','));      }  });  var output = csvData.join('\n');  var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(output);  $link.attr("href", uri);}

Notes:

  • It uses "th" tags for headings. If they are not present, they are notadded.
  • This code detects numbers in the format: -####.## (You will need modify the code in order to accept other formats, e.g. using commas).

UPDATE:

My previous implementation worked fine but it didn't set the csv filename. The code was modified to use a filename but it requires an < a > element. It seems that you can't dynamically generate the < a > element and fire the "click" event (perhaps security reasons?).

DEMO

http://jsfiddle.net/nLj74t0f/

(Unfortunately jsfiddle fails to generate the file and instead it throws an error: 'please use POST request', don't let that error stop you from testing this code in your application).


I recently posted a free software library for this: "html5csv.js" -- GitHub

It is intended to help streamline the creation of small simulator appsin Javascript that might need to import or export csv files, manipulate, display, editthe data, perform various mathematical procedures like fitting, etc.

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

The CSV.begin() call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download() generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

According to caniuse IE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob() internally, as suggested by @Manu Sharma