excelHelper.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import Vue from 'vue'
  2. import FileSaver from "file-saver";
  3. import XLSX from "xlsx";
  4. export default {
  5. /**
  6. * @param tableId 要导出的表格ID
  7. * @param fileName 文件导出名称
  8. * @param fileType 文件类型
  9. * @param rawFlag - true 导出的内容只做解析,不进行格式转换
  10. * @returns {*}
  11. */
  12. exportExcel(tableId,fileName,fileType,rawFlag) {
  13. let fix = document.querySelector('.el-table__fixed');
  14. let wb;
  15. /* 判断要导出的节点中是否有fixed的表格,如果有,转换excel时先将该dom移除,然后append回去 */
  16. if(fix){
  17. wb = XLSX.utils.table_to_book(document.querySelector("#"+tableId).removeChild(fix),{raw:rawFlag});
  18. document.querySelector("#"+tableId).appendChild(fix);
  19. }else{
  20. wb = XLSX.utils.table_to_book(document.querySelector("#"+tableId),{raw:rawFlag});
  21. }
  22. /* 获取二进制字符串作为输出 */
  23. let wbout = XLSX.write(wb, {
  24. bookType: "xlsx",
  25. bookSST: true,
  26. type: "array"
  27. });
  28. try {
  29. FileSaver.saveAs(
  30. //Blob 对象表示一个不可变、原始数据的类文件对象。
  31. //Blob 表示的不一定是JavaScript原生格式的数据。
  32. //File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
  33. //返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
  34. new Blob([wbout], { type: "application/octet-stream" }),
  35. //设置导出文件名称
  36. fileName + fileType
  37. );
  38. } catch (e) {
  39. if (typeof console !== "undefined") console.log(e, wbout);
  40. }
  41. return wbout;
  42. }
  43. }