exportExcel.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import notification from 'ant-design-vue/es/notification'
  2. import moment from 'moment'
  3. // 导出excel
  4. /*
  5. *url: 数据请求接口
  6. *params: 请求参数
  7. *fileName: 导出文件名称
  8. *callback: 回调函数
  9. */
  10. export const hdExportExcel = function (url, params, fileName, callback) {
  11. url(params).then(res => {
  12. if (res.type == 'application/json') {
  13. var reader = new FileReader()
  14. reader.addEventListener('loadend', function () {
  15. const obj = JSON.parse(reader.result)
  16. notification.error({
  17. message: '提示',
  18. description: obj.message
  19. })
  20. })
  21. reader.readAsText(res)
  22. } else {
  23. downloadExcel(res, fileName)
  24. }
  25. callback()
  26. })
  27. }
  28. // 导出下载excel
  29. export const downloadExcel = function (data, fileName) {
  30. if (!data) { return }
  31. const a = moment().format('YYYYMMDDHHmmss')
  32. const fname = fileName + a
  33. const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
  34. if (window.navigator && window.navigator.msSaveOrOpenBlob) {
  35. navigator.msSaveBlob(blob, fname + '.xlsx')
  36. } else {
  37. const link = document.createElement('a')
  38. link.style.display = 'none'
  39. var href = URL.createObjectURL(blob)
  40. link.href = href
  41. link.setAttribute('download', fname + '.xlsx')
  42. document.body.appendChild(link)
  43. link.click()
  44. document.body.removeChild(link)
  45. window.URL.revokeObjectURL(href) // 释放掉blob对象
  46. }
  47. }