Introduction

This example shows how to export an HTML table to an Excel sheet using jquery table2excel plugin.

What is table2excel?

table2excel is a jQuery Plugin. it is used to export HTML tables to Excel sheets.

How to Include table2excel jQuery Plugin Within HTML File

  1. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  2. <script src="table2excel.js" type="text/javascript"></script>

table2excel.js Markup

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

HTML Markup

Now, create another text document within the root directory of your project and save it with the name of "Example.html".
After this, write the following code within your created Example.html file and save it.
  1. <html
  2. xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title></title>
  5. <style type="text/css">
  6. body
  7. {
  8. font-family: Arial;
  9. font-size: 10pt;
  10. }
  11. table
  12. {
  13. border: 1px solid #ccc;
  14. border-collapse: collapse;
  15. }
  16. table th
  17. {
  18. background-color: #ff7f00;
  19. color: #fff;
  20. font-weight: bold;
  21. }
  22. table th, table td
  23. {
  24. padding: 5px;
  25. border: 1px solid #ccc;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <table id="tblEmployee" cellspacing="0" cellpadding="0">
  31. <tr>
  32. <th>Employee Id</th>
  33. <th>Employee Name</th>
  34. <th>Department</th>
  35. </tr>
  36. <tr>
  37. <td>1</td>
  38. <td>Nikunj Satasiya</td>
  39. <td>Asp.Net</td>
  40. </tr>
  41. <tr>
  42. <td>2</td>
  43. <td>Hiren Dobariya</td>
  44. <td>PHP</td>
  45. </tr>
  46. <tr>
  47. <td>3</td>
  48. <td>Vivek Ghadiya</td>
  49. <td>Android</td>
  50. </tr>
  51. <tr>
  52. <td>4</td>
  53. <td>Pratik Pansuriya</td>
  54. <td>SEO</td>
  55. </tr>
  56. </table>
  57. <br />
  58. <input type="button" id="btnExporttoExcel" value="Export To Excel" />
  59. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  60. <script src="table2excel.js" type="text/javascript"></script>
  61. <script type="text/javascript">
  62. $(function () {
  63. $("#btnExporttoExcel").click(function () {
  64. $("#tblEmployee").table2excel({
  65. filename: "Your_File_Name.xls"
  66. });
  67. });
  68. });
  69. </script>
  70. </body>
  71. </html>
NOTE
At the end of table tag </table>, you need to add the following script.
  1. $("#yourHtmTable").table2excel({
  2. exclude: ".excludeThisClass",
  3. name: "Worksheet Name",
  4. filename: "SomeFile"
  5. });
Screenshots/Output
Output
The screen after exporting HTML table to Excel sheet.
Output
Summary
When the Export to Excel button is clicked, the jQuery table2excel plugin is applied to the created HTML table. The jQuery table2excel plugin accepts the file name as a parameter which sets the name of the Excel file.