jquery-tableexport
Version:
This is a simple jQuery plug-in that allows exporting html tables to: CSV, XLS, TXT, SQL.
6 lines • 2.56 kB
JavaScript
/*!
* jQuery Table Export v1.0.1
* https://github.com/Archakov06/jQuery-tableExport
* Released under the MIT License.
*/
!function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={exports:{},id:o,loaded:!1};return e[o].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t){!function(e){e.fn.tableExport=function(t){function n(){var e=i.find("thead th"),t=[];return e.each(function(e,n){c.length?c.forEach(function(o){o==e+1&&t.push(n.innerText)}):t.push(n.innerText)}),t}function o(){var t=i.find("tbody tr"),n=[];return t.each(function(t,o){var r=[];if(c.length)c.forEach(function(t){r.push(e(o).find("td:nth-child("+t+")").text())}),n.push(r);else{var a=e(o).find("td");a.each(function(e,t){r.push(t.innerText)}),n.push(r)}}),n}function r(e,t,n){var o=document.createElement("a"),r=new Blob([e],{type:l[n]});o.href=URL.createObjectURL(r);var a=new Date,i=["DD:"+a.getDate(),"MM:"+(a.getMonth()+1),"YY:"+a.getFullYear(),"hh:"+a.getHours(),"mm:"+a.getMinutes(),"ss:"+a.getSeconds()];i.forEach(function(e){var n=e.split(":")[0],o=e.split(":")[1],r=new RegExp("%"+n+"%","g");t=t.replace(r,o)}),o.download=t+"."+n,document.body.appendChild(o),o.click(),navigator.userAgent.toLowerCase().match(/firefox/)||o.remove()}var a=e.extend({filename:"table",format:"csv",cols:"",head_delimiter:";",column_delimiter:";",onbefore:function(e){},onafter:function(e){}},t),t=e.extend(a,t),i=e(this),c=t.cols?t.cols.split(","):[],f="",l={csv:"text/csv",txt:"text/plain",xls:"application/vnd.ms-excel",json:"application/json"};if(!("function"==typeof t.onbefore&&"function"==typeof t.onafter&&t.format&&t.head_delimiter&&t.column_delimiter&&t.filename))return console.error("One of the parameters is incorrect."),!1;switch(t.onafter(i),t.format){case"csv":var d=n(),u=o();f+=d.join(t.head_delimiter)+"\n",u.forEach(function(e,n){f+=e.join(t.column_delimiter)+"\n"});break;case"txt":var d=n(),u=o();f+=d.join(t.head_delimiter)+"\n",u.forEach(function(e,n){f+=e.join(t.column_delimiter)+"\n"});break;case"xls":var d=n(),u=o();template="<table><thead>%thead%</thead><tbody>%tbody%</tbody></table>";var s="";d.forEach(function(e,t){s+="<th>"+e+"</th>"}),template=template.replace("%thead%",s),s="",u.forEach(function(e,t){s+="<tr>",e.forEach(function(e,t){s+="<td>"+e+"</td>"}),s+="</tr>"}),template=template.replace("%tbody%",s),f=template;break;case"sql":var d=n(),u=o();u.forEach(function(e,t){f+="INSERT INTO table ("+d.join(",")+") VALUES ('"+e.join("','")+"');"})}r(f,t.filename,t.format),t.onbefore(i)}}(jQuery)}]);