jquery.table2excel.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /*
  2. * jQuery table2excel - v1.1.2
  3. * jQuery plugin to export an .xls file in browser from an HTML table
  4. * https://github.com/rainabba/jquery-table2excel
  5. *
  6. * Made by rainabba
  7. * Under MIT License
  8. */
  9. //table2excel.js
  10. (function ( $, window, document, undefined ) {
  11. var pluginName = "table2excel",
  12. defaults = {
  13. exclude: ".noExl",
  14. name: "Table2Excel",
  15. filename: "table2excel",
  16. fileext: ".xls",
  17. exclude_img: true,
  18. exclude_links: true,
  19. exclude_inputs: true,
  20. preserveColors: false
  21. };
  22. // The actual plugin constructor
  23. function Plugin ( element, options ) {
  24. this.element = element;
  25. // jQuery has an extend method which merges the contents of two or
  26. // more objects, storing the result in the first object. The first object
  27. // is generally empty as we don't want to alter the default options for
  28. // future instances of the plugin
  29. //
  30. this.settings = $.extend( {}, defaults, options );
  31. this._defaults = defaults;
  32. this._name = pluginName;
  33. this.init();
  34. }
  35. Plugin.prototype = {
  36. init: function () {
  37. var e = this;
  38. var utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">";
  39. e.template = {
  40. head: "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">" + utf8Heading + "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>",
  41. sheet: {
  42. head: "<x:ExcelWorksheet><x:Name>",
  43. tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
  44. },
  45. mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
  46. table: {
  47. head: "<table>",
  48. tail: "</table>"
  49. },
  50. foot: "</body></html>"
  51. };
  52. e.tableRows = [];
  53. // Styling variables
  54. var additionalStyles = "";
  55. var compStyle = null;
  56. // get contents of table except for exclude
  57. $(e.element).each( function(i,o) {
  58. var tempRows = "";
  59. $(o).find("tr").not(e.settings.exclude).each(function (i,p) {
  60. // Reset for this row
  61. additionalStyles = "";
  62. // Preserve background and text colors on the row
  63. if(e.settings.preserveColors){
  64. compStyle = getComputedStyle(p);
  65. additionalStyles += (compStyle && compStyle.backgroundColor ? "background-color: " + compStyle.backgroundColor + ";" : "");
  66. additionalStyles += (compStyle && compStyle.color ? "color: " + compStyle.color + ";" : "");
  67. }
  68. // Create HTML for Row
  69. tempRows += "<tr style='" + additionalStyles + "'>";
  70. // Loop through each TH and TD
  71. $(p).find("td,th").not(e.settings.exclude).each(function (i,q) { // p did not exist, I corrected
  72. // Reset for this column
  73. additionalStyles = "";
  74. // Preserve background and text colors on the row
  75. if(e.settings.preserveColors){
  76. compStyle = getComputedStyle(q);
  77. additionalStyles += (compStyle && compStyle.backgroundColor ? "background-color: " + compStyle.backgroundColor + ";" : "");
  78. additionalStyles += (compStyle && compStyle.color ? "color: " + compStyle.color + ";" : "");
  79. }
  80. var rc = {
  81. rows: $(this).attr("rowspan"),
  82. cols: $(this).attr("colspan"),
  83. flag: $(q).find(e.settings.exclude)
  84. };
  85. if( rc.flag.length > 0 ) {
  86. tempRows += "<td> </td>"; // exclude it!!
  87. } else {
  88. tempRows += "<td";
  89. if( rc.rows > 0) {
  90. tempRows += " rowspan='" + rc.rows + "' ";
  91. }
  92. if( rc.cols > 0) {
  93. tempRows += " colspan='" + rc.cols + "' ";
  94. }
  95. if(additionalStyles){
  96. tempRows += " style='" + additionalStyles + "'";
  97. }
  98. tempRows += ">" + $(q).html() + "</td>";
  99. }
  100. });
  101. tempRows += "</tr>";
  102. });
  103. // exclude img tags
  104. if(e.settings.exclude_img) {
  105. tempRows = exclude_img(tempRows);
  106. }
  107. // exclude link tags
  108. if(e.settings.exclude_links) {
  109. tempRows = exclude_links(tempRows);
  110. }
  111. // exclude input tags
  112. if(e.settings.exclude_inputs) {
  113. tempRows = exclude_inputs(tempRows);
  114. }
  115. e.tableRows.push(tempRows);
  116. });
  117. e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);
  118. },
  119. tableToExcel: function (table, name, sheetName) {
  120. var e = this, fullTemplate="", i, link, a;
  121. e.format = function (s, c) {
  122. return s.replace(/{(\w+)}/g, function (m, p) {
  123. return c[p];
  124. });
  125. };
  126. sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName;
  127. e.ctx = {
  128. worksheet: name || "Worksheet",
  129. table: table,
  130. sheetName: sheetName
  131. };
  132. fullTemplate= e.template.head;
  133. if ( $.isArray(table) ) {
  134. Object.keys(table).forEach(function(i){
  135. //fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
  136. fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
  137. });
  138. }
  139. fullTemplate += e.template.mid;
  140. if ( $.isArray(table) ) {
  141. Object.keys(table).forEach(function(i){
  142. fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
  143. });
  144. }
  145. fullTemplate += e.template.foot;
  146. for (i in table) {
  147. e.ctx["table" + i] = table[i];
  148. }
  149. delete e.ctx.table;
  150. var isIE = navigator.appVersion.indexOf("MSIE 10") !== -1 || (navigator.userAgent.indexOf("Trident") !== -1 && navigator.userAgent.indexOf("rv:11") !== -1); // this works with IE10 and IE11 both :)
  151. //if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // this works ONLY with IE 11!!!
  152. if (isIE) {
  153. if (typeof Blob !== "undefined") {
  154. //use blobs if we can
  155. fullTemplate = e.format(fullTemplate, e.ctx); // with this, works with IE
  156. fullTemplate = [fullTemplate];
  157. //convert to array
  158. var blob1 = new Blob(fullTemplate, { type: "text/html" });
  159. window.navigator.msSaveBlob(blob1, getFileName(e.settings) );
  160. } else {
  161. //otherwise use the iframe and save
  162. //requires a blank iframe on page called txtArea1
  163. txtArea1.document.open("text/html", "replace");
  164. txtArea1.document.write(e.format(fullTemplate, e.ctx));
  165. txtArea1.document.close();
  166. txtArea1.focus();
  167. sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings) );
  168. }
  169. } else {
  170. var blob = new Blob([e.format(fullTemplate, e.ctx)], {type: "application/vnd.ms-excel"});
  171. window.URL = window.URL || window.webkitURL;
  172. link = window.URL.createObjectURL(blob);
  173. a = document.createElement("a");
  174. a.download = getFileName(e.settings);
  175. a.href = link;
  176. document.body.appendChild(a);
  177. a.click();
  178. document.body.removeChild(a);
  179. }
  180. return true;
  181. }
  182. };
  183. function getFileName(settings) {
  184. return ( settings.filename ? settings.filename : "table2excel" );
  185. }
  186. // Removes all img tags
  187. function exclude_img(string) {
  188. var _patt = /(\s+alt\s*=\s*"([^"]*)"|\s+alt\s*=\s*'([^']*)')/i;
  189. return string.replace(/<img[^>]*>/gi, function myFunction(x){
  190. var res = _patt.exec(x);
  191. if (res !== null && res.length >=2) {
  192. return res[2];
  193. } else {
  194. return "";
  195. }
  196. });
  197. }
  198. // Removes all link tags
  199. function exclude_links(string) {
  200. return string.replace(/<a[^>]*>|<\/a>/gi, "");
  201. }
  202. // Removes input params
  203. function exclude_inputs(string) {
  204. var _patt = /(\s+value\s*=\s*"([^"]*)"|\s+value\s*=\s*'([^']*)')/i;
  205. return string.replace(/<input[^>]*>|<\/input>/gi, function myFunction(x){
  206. var res = _patt.exec(x);
  207. if (res !== null && res.length >=2) {
  208. return res[2];
  209. } else {
  210. return "";
  211. }
  212. });
  213. }
  214. $.fn[ pluginName ] = function ( options ) {
  215. var e = this;
  216. e.each(function() {
  217. if ( !$.data( e, "plugin_" + pluginName ) ) {
  218. $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
  219. }
  220. });
  221. // chain jQuery functions
  222. return e;
  223. };
  224. })( jQuery, window, document );