exports.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. function exportExcel(JSONData, FileName, title, filter) {
  2. if (!JSONData) return;
  3. //转化json为object
  4. var arrData = typeof JSONData != "object" ? JSON.parse(JSONData) : JSONData;
  5. var excel = "<table>";
  6. //设置表头
  7. var row = "<tr>";
  8. if (title) { //使用标题项
  9. for (var i in title) {
  10. row += "<th align='center'>" + title[i] + "</th>";
  11. }
  12. } else {//不使用标题项
  13. for (var i in arrData[0]) {
  14. row += "<th align='center'>" + i + "</th>";
  15. }
  16. }
  17. excel += row + "</tr>";
  18. //设置数据
  19. for (var i = 0; i < arrData.length; i++) {
  20. var row = "<tr>";
  21. for (var index in arrData[i]) {
  22. //判断是否有过滤行
  23. if (filter) {
  24. if (filter.indexOf(index) == -1) {
  25. var value = arrData[i][index] == null ? "" : arrData[i][index];
  26. row += "<td>" + value + "</td>";
  27. }
  28. } else {
  29. var value = arrData[i][index] == null ? "" : arrData[i][index];
  30. row += "<td align='center'>" + value + "</td>";
  31. }
  32. }
  33. excel += row + "</tr>";
  34. }
  35. excel += "</table>";
  36. var excelFile =
  37. "<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'>";
  38. excelFile +=
  39. '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
  40. excelFile +=
  41. '<meta http-equiv="content-type" content="application/vnd.ms-excel';
  42. excelFile += '; charset=UTF-8">';
  43. excelFile += "<head>";
  44. excelFile += "<!--[if gte mso 9]>";
  45. excelFile += "<xml>";
  46. excelFile += "<x:ExcelWorkbook>";
  47. excelFile += "<x:ExcelWorksheets>";
  48. excelFile += "<x:ExcelWorksheet>";
  49. excelFile += "<x:Name>";
  50. excelFile += "{worksheet}";
  51. excelFile += "</x:Name>";
  52. excelFile += "<x:WorksheetOptions>";
  53. excelFile += "<x:DisplayGridlines/>";
  54. excelFile += "</x:WorksheetOptions>";
  55. excelFile += "</x:ExcelWorksheet>";
  56. excelFile += "</x:ExcelWorksheets>";
  57. excelFile += "</x:ExcelWorkbook>";
  58. excelFile += "</xml>";
  59. excelFile += "<![endif]-->";
  60. excelFile += "</head>";
  61. excelFile += "<body>";
  62. excelFile += excel;
  63. excelFile += "</body>";
  64. excelFile += "</html>";
  65. var uri =
  66. "data:application/vnd.ms-excel;charset=utf-8," +
  67. encodeURIComponent(excelFile);
  68. var link = document.createElement("a");
  69. link.href = uri;
  70. link.style = "visibility:hidden";
  71. link.download = FileName + ".xls";
  72. document.body.appendChild(link);
  73. link.click();
  74. document.body.removeChild(link);
  75. }