HtmlTbale2Excel.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import XLSX from 'xlsx'
  2. /**
  3. * HTMLtabl转excel文件
  4. */
  5. class HtmlTbale2ExcelService {
  6. /**
  7. * 导出excel
  8. * @param {string} fileName 保存文件名
  9. * @param {HTMLElement} table table表格DOM
  10. */
  11. outfile(fileName, table) {
  12. try {
  13. const sheet1 = XLSX.utils.table_to_sheet(table, { raw: true })
  14. const blob2 = this.sheets2book2blob([ sheet1 ])
  15. this.openDownloadDialog(blob2, `${fileName}.xlsx`)
  16. } catch (error) {
  17. console.error('导出错误')
  18. }
  19. }
  20. /**
  21. * sheet转blob
  22. * @param {Array<any>} params sheet参数arr|obj
  23. */
  24. sheets2book2blob(params) {
  25. if (params && params.length > 0) {
  26. const workbook = {
  27. SheetNames: [],
  28. Sheets: {}
  29. }
  30. // 参数两种模式纯arr || arrobj
  31. for (let k = 0; k < params.length; k++) {
  32. const el = params[k]
  33. if (el.db && el.name) {
  34. workbook.SheetNames.push(el.name)
  35. workbook.Sheets[el.name] = el.db
  36. } else {
  37. workbook.SheetNames.push(`sheet${k}`)
  38. workbook.Sheets[`sheet${k}`] = el
  39. }
  40. }
  41. // 生成excel的配置项
  42. const wopts = {
  43. bookType: 'xlsx', // 要生成的文件类型
  44. bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
  45. type: 'binary'
  46. }
  47. const wbout = XLSX.write(workbook, wopts)
  48. const blob = new Blob([ this.s2ab(wbout) ], { type: 'application/octet-stream' })
  49. return blob
  50. }
  51. console.error('参数错误(need arr and arr obj)')
  52. }
  53. /**
  54. * 字符串转ArrayBuffer
  55. * @param {string} s 字符串
  56. */
  57. s2ab(s) {
  58. const buf = new ArrayBuffer(s.length)
  59. const view = new Uint8Array(buf)
  60. for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
  61. return buf
  62. }
  63. /**
  64. * 下载
  65. * @param {any} url 文件blob
  66. * @param {string} fileName 文件名
  67. */
  68. openDownloadDialog(url, fileName) {
  69. if (typeof url === 'object' && url instanceof Blob) {
  70. url = URL.createObjectURL(url) // 创建blob地址
  71. }
  72. const aLink = document.createElement('a')
  73. aLink.href = url
  74. aLink.download = fileName || '' // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
  75. let event
  76. if (window.MouseEvent) event = new MouseEvent('click')
  77. else {
  78. event = document.createEvent('MouseEvents')
  79. event.initMouseEvent(
  80. 'click',
  81. true,
  82. false,
  83. window,
  84. 0,
  85. 0,
  86. 0,
  87. 0,
  88. 0,
  89. false,
  90. false,
  91. false,
  92. false,
  93. 0,
  94. null
  95. )
  96. }
  97. aLink.dispatchEvent(event)
  98. }
  99. }
  100. export default new HtmlTbale2ExcelService()