JQuery - Export table to CSV file

I needed to implement downloading table data as csv file. Normally, we're doing it on server side. But I thought it violates the DRY principle. And it occurs server load.

I looked for exporting CSV by Javascript. And I found Table2CSV (http://www.kunalbabre.com/projects/table2CSV.php). But it isn't downloading as a file.

I saw "Google Image Search" uses Data URI scheme to show the preview of their search results. You can see about "Data URI scheme" on here : http://en.wikipedia.org/wiki/Data_URI_scheme

So, I could write very simple codes fully client side CSV export function using it as below :

(function($) {
 $.fn.exportAsCSV = function() {
  var error = this.attr("tagName") != "TABLE" && console && console.error("This function only supports TABLE tag.");
  if(error !== false) {
   return;
  }
  var csv = [];
  // header
  csv.push('"' + $("th", this).map(function() {
    return $(this).text();
  }).get().join('","') + '"');
  // body
  $("tr:gt(0)", this).each(function() {
   csv.push('"' + $("td", this).map(function() {
    return $(this).text();
   }).get().join('","') + '"');
  });
  location.href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv.join("\r\n"));
  return this;
 }
})(jQuery);
Try out a demo : http://jsfiddle.net/zKPML/embedded/result/

댓글

이 블로그의 인기 게시물

엄마 놀이

단위테스트를 위한 주민등록번호 생성

프로그래머가 되기까지...