ExportExcel.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. var idTmr;
  2. function getExplorer() {
  3. var explorer = window.navigator.userAgent;
  4. //ie
  5. if (explorer.indexOf("MSIE") >= 0) {
  6. return 'ie';
  7. }
  8. //firefox
  9. else if (explorer.indexOf("Firefox") >= 0) {
  10. return 'Firefox';
  11. }
  12. //Chrome
  13. else if (explorer.indexOf("Chrome") >= 0) {
  14. return 'Chrome';
  15. }
  16. //Opera
  17. else if (explorer.indexOf("Opera") >= 0) {
  18. return 'Opera';
  19. }
  20. //Safari
  21. else if (explorer.indexOf("Safari") >= 0) {
  22. return 'Safari';
  23. }
  24. }
  25. function ExportExcel(tableid, name,style) {//整个表格拷贝到EXCEL中
  26. if (getExplorer() == 'ie') {
  27. var curTbl = document.getElementById(tableid);
  28. var oXL = new ActiveXObject("Excel.Application");
  29. //创建AX对象excel
  30. var oWB = oXL.Workbooks.Add();
  31. //获取workbook对象
  32. var xlsheet = oWB.Worksheets(1);
  33. //激活当前sheet
  34. var sel = document.body.createTextRange();
  35. sel.moveToElementText(curTbl);
  36. //把表格中的内容移到TextRange中
  37. sel.select;
  38. //全选TextRange中内容
  39. sel.execCommand("Copy");
  40. //复制TextRange中内容
  41. xlsheet.Paste();
  42. //粘贴到活动的EXCEL中
  43. oXL.Visible = true;
  44. //设置excel可见属性
  45. try {
  46. var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  47. } catch (e) {
  48. print("Nested catch caught " + e);
  49. } finally {
  50. oWB.SaveAs(fname);
  51. oWB.Close(savechanges = false);
  52. //xls.visible = false;
  53. oXL.Quit();
  54. oXL = null;
  55. //结束excel进程,退出完成
  56. //window.setInterval("Cleanup();",1);
  57. idTmr = window.setInterval("Cleanup();", 1);
  58. }
  59. } else {
  60. //tableToExcel(tableid, name, style);
  61. tableToExcel2(tableid, name, style);
  62. }
  63. }
  64. function Cleanup() {
  65. window.clearInterval(idTmr);
  66. CollectGarbage();
  67. }
  68. /*
  69. template : 定义文档的类型,相当于html页面中顶部的<!DOCTYPE> 声明。(个人理解,不确定)
  70. encodeURIComponent:解码
  71. unescape() 函数:对通过 escape() 编码的字符串进行解码。
  72. window.btoa(window.encodeURIComponent(str)):支持汉字进行解码。
  73. \w :匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’
  74. replace()方法:用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
  75. {(\w+)}:匹配所有 {1个或更多字符} 形式的字符串;此处匹配输出内容是 “worksheet”
  76. 正则中的() :是为了提取匹配的字符串。表达式中有几个()就有几个相应的匹配字符串。
  77. 讲解(/{(\w+)}/g, function(m, p) { return c[p]; } :
  78. /{(\w+)}/g 匹配出所有形式为“{worksheet}”的字符串;
  79. function参数: m 正则所匹配到的内容,即“worksheet”;
  80. p 正则表达式中分组的内容,即“(\w+)”分组中匹配到的内容,为“worksheet”;
  81. c :为object,见下图3
  82. c[p] : 为“worksheet”
  83. */
  84. var tableToExcel = (function () {
  85. var uri = 'data:application/vnd.ms-excel;base64,',
  86. template = '<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"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>${worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->{style}</head><body><table>{table}</table></body></html>',
  87. base64 = function (s) {
  88. return window.btoa(unescape(encodeURIComponent(s)));
  89. },
  90. // 下面这段函数作用是:将template中的变量替换为页面内容ctx获取到的值
  91. format = function (s, c) {
  92. return s.replace(/{(\w+)}/g,
  93. function (m, p) {
  94. return c[p];
  95. }
  96. );
  97. };
  98. return function (table, name, style) {
  99. //if (!table.nodeType) {
  100. // table = document.getElementById(table);
  101. //}
  102. var tableHtml = $("#" + table).html();
  103. // 获取表单的名字和表单查询的内容
  104. var ctx = { worksheet: name || 'Worksheet', table: tableHtml,style:$("#"+style).html() };
  105. // format()函数:通过格式操作使任意类型的数据转换成一个字符串
  106. // base64():进行编码
  107. console.log(format(template, ctx));
  108. var ex = getExplorer();
  109. if (ex == 'Firefox' || ex == 'Chrome') {
  110. console.log(format(template, ctx));
  111. var blob = new Blob([format(template, ctx)]);
  112. a.href = URL.createObjectURL(blob);//解决由于数据量太大导致chrome导出出现网络错误(由于url长度限制)
  113. $("body").append('<a id="cLink" href="' +
  114. uri +
  115. base64(format(template, ctx)) +
  116. '" download="' +
  117. name +
  118. Math.floor(Math.random() * 100 + 1) +
  119. '.xls"></a>');
  120. $("#cLink")[0].click();
  121. $("#cLink").remove();
  122. } else {
  123. window.location.href = uri + base64(format(template, ctx));
  124. }
  125. //window.location.href = uri + base64(format(template, ctx));
  126. /*var exportA = document.createElement('a');
  127. exportA.setAttribute('download',name+'123.xls');
  128. exportA.setAttribute('href', uri + base64(format(template, ctx)));
  129. exportA.click(); */
  130. }
  131. })();
  132. var tableToExcel2 = function (table, fileName, style) {
  133. var format = function (s, c) {
  134. return s.replace(/{(\w+)}/g,
  135. function (m, p) {
  136. return c[p];
  137. }
  138. );
  139. };
  140. var uri = 'data:application/vnd.ms-excel;base64,'
  141. , fileName = fileName || 'excelexport'
  142. , template = '<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"><head><meta name="renderer" content="webkit"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->{style}</head><body><table>{table}</table></body></html>';
  143. var tableHtml = $("#" + table).html();
  144. var ctx = { worksheet: 'Worksheet', table: tableHtml, style: $("#" + style).html() };
  145. var a = document.createElement('a');
  146. document.body.appendChild(a);
  147. a.hreflang = 'zh';
  148. a.charset = 'utf8';
  149. a.type = "application/vnd.ms-excel";
  150. var blob = new Blob([format(template, ctx)]);
  151. a.href = URL.createObjectURL(blob);//解决由于数据量太大导致chrome导出出现网络错误(由于url长度限制)
  152. // a.href = uri + Base64.encode(format(template,ctx));
  153. a.target = '_blank';
  154. a.download = fileName + '.xls';
  155. a.tableBorder = 1;
  156. a.click();
  157. };