JavaScript导出Excel类

  1. var ExcelHelper = {};
  2. ExcelHelper.getBrowserName = function() {
  3. var ua = window.navigator.userAgent;
  4. //ie
  5. if (ua.indexOf("MSIE") >= 0) {
  6. return 'ie';
  7. }
  8. //firefox
  9. else if (ua.indexOf("Firefox") >= 0) {
  10. return 'Firefox';
  11. }
  12. //Chrome
  13. else if (ua.indexOf("Chrome") >= 0) {
  14. return 'Chrome';
  15. }
  16. //Opera
  17. else if (ua.indexOf("Opera") >= 0) {
  18. return 'Opera';
  19. }
  20. //Safari
  21. else if (ua.indexOf("Safari") >= 0) {
  22. return 'Safari';
  23. }
  24. }
  25. ExcelHelper.tableToExcel = (function() {
  26. var uri = 'data:application/vnd.ms-excel;base64,',
  27. 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]--></head><body><table>{table}</table></body></html>',
  28. base64 = function(s) {
  29. return window.btoa(unescape(encodeURIComponent(s)))
  30. },
  31. format = function(s, c) {
  32. return s.replace(/{(\w+)}/g,
  33. function(m, p) {
  34. return c[p];
  35. })
  36. }
  37. return function(table, name) {
  38. var ctx = {
  39. "worksheet": name || 'Worksheet',
  40. table: table.innerHTML
  41. }
  42. window.location.href = uri + base64(format(template, ctx))
  43. }
  44. })();
  45. ExcelHelper.CreateExcelByTable = function(table) {
  46. var bn = this.getBrowserName();
  47. if (bn == "ie") {
  48. var ax = new ActiveXObject("Excel.Application");
  49. var wb = ax.Workbooks.Add();
  50. var sheet = wb.Worksheets(1);
  51. var tr = document.body.createTextRange();
  52. tr.moveToElementText(table);
  53. tr.select();
  54. tr.execCommand("Copy");
  55. sheet.Paste();
  56. ax.Visible = true;
  57. var si = null;
  58. var cleanup = function() {
  59. if (si) {
  60. window.clearInterval(si);
  61. }
  62. }
  63. try {
  64. var fname = ax.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  65. } catch (e) {
  66. print("Nested catch caught " + e);
  67. } finally {
  68. wb.SaveAs(fname);
  69. var savechanges = false;
  70. wb.Close(savechanges);
  71. ax.Quit();
  72. ax = null;
  73. si = window.setInterval(cleanup, 1);
  74. }
  75. } else {
  76. this.tableToExcel(table);
  77. }
  78. }

测试代码

  1. var table = document.getElementById('table_id');
  2. ExcelHelper.CreateExcelByTable(table);