UNPKG

react-easy-export

Version:

A React library for easily exporting data to CSV, PDF, and Excel formats.

3 lines (2 loc) 2.64 kB
"use strict";function t(r){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(r)}Object.defineProperty(exports,"__esModule",{value:!0});exports.exportToCSV=function(r){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"data.csv",e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:",";if(!Array.isArray(r)||!r.length)throw new Error("Invalid data format. Expected an array of objects or a 2D array.");var n=[],a="";if("object"!==t(r[0])||Array.isArray(r[0])){if(!Array.isArray(r[0]))throw new Error("Invalid data format. Expected an array of objects or a 2D array.");r.forEach((function(t){a+=t.map((function(t){return"string"==typeof t&&t.includes(e)&&(t='"'.concat(t,'"')),t})).join(e)+"\r\n"}))}else n=Object.keys(r[0]),a+=n.join(e)+"\r\n",r.forEach((function(t){var r=n.map((function(r){var o=t[r];return"string"==typeof o&&o.includes(e)&&(o='"'.concat(o,'"')),o}));a+=r.join(e)+"\r\n"}));var c=new Blob([a],{type:"text/csv;charset=utf-8;"}),i=document.createElement("a"),d=URL.createObjectURL(c);i.setAttribute("href",d),i.setAttribute("download",o),document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(d)},exports.exportToExcel=function(r){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"data.xls";if(!Array.isArray(r)||!r.length)throw new Error("Invalid data format. Expected an array of objects or a 2D array.");var e='<table border="1">';if("object"!==t(r[0])||Array.isArray(r[0])){if(!Array.isArray(r[0]))throw new Error("Invalid data format. Expected an array of objects or a 2D array.");r.forEach((function(t){e+="<tr>",t.forEach((function(t){e+="<td>".concat(t||"","</td>")})),e+="</tr>"}))}else{var n=Object.keys(r[0]);e+="<tr>",n.forEach((function(t){e+="<th>".concat(t,"</th>")})),e+="</tr>",r.forEach((function(t){e+="<tr>",n.forEach((function(r){e+="<td>".concat(t[r]||"","</td>")})),e+="</tr>"}))}e+="</table>";var a="data:application/vnd.ms-excel;charset=utf-8,"+encodeURIComponent(e),c=document.createElement("a");c.setAttribute("href",a),c.setAttribute("download",o),document.body.appendChild(c),c.click(),document.body.removeChild(c)},exports.exportToPDF=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"data.pdf",o=window.open("","_blank");o?(o.document.write(t),o.document.title=r,o.document.close(),o.onload=function(){o.print(),o.onafterprint=function(){o.close()}}):alert("Please allow popups to print content.")}; //# sourceMappingURL=react-easy-export.js.map