downTable.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import FileSaver from 'file-saver'
  2. import XLSX from 'xlsx'
  3. import { Message, MessageBox } from 'element-ui'
  4. // 导出表格
  5. /**
  6. * @param { String } id 表格id
  7. * @param { Array } width 配置生成文件表格所占的字符也就是表格每一行的宽度
  8. * @param { String } name 生成文件名字
  9. */
  10. const downTable = (id, width, name) => {
  11. name = name + '.xlsx' || 'test.xlsx'
  12. const excel = exportExcel(document.getElementById(id), width, name)
  13. if (excel) {
  14. Message({
  15. message: '导出成功',
  16. type: 'success',
  17. duration: 3 * 1000
  18. })
  19. }
  20. }
  21. /**
  22. * 导出表格为excel格式
  23. * @param { DOM } ele // document.getElementById('table')
  24. * @param { string } fileName // test.xlsx
  25. */
  26. function exportExcel(ele, wscols, fileName) {
  27. var fix = document.querySelector('.el-table__fixed');
  28. /* 从表生成工作簿对象 */
  29. let wb;
  30. if (fix) {
  31. wb = XLSX.utils.table_to_book(ele.removeChild(fix));
  32. ele.appendChild(fix);
  33. } else {
  34. wb = XLSX.utils.table_to_book(ele);
  35. }
  36. console.log(wb.Sheets.Sheet1, Object.keys(wb.Sheets.Sheet1).filter(item => /^\D\d$/.test(item)))
  37. // 修改表格内容宽度
  38. wb.Sheets.Sheet1['!cols'] = wscols;
  39. // 新增样式 xlsl-style引入有问题暂时注释
  40. // const Sheet1Key = wb.Sheets.Sheet1
  41. // Object.keys(Sheet1Key).forEach(item => {
  42. // if (/^\D\d$/.test(item)) {
  43. // Sheet1Key[item].s = {
  44. // font: {
  45. // color: {
  46. // rgb: 'FF4F81BD' //字体颜色
  47. // }
  48. // },
  49. // alignment: {
  50. // horizontal: 'center'
  51. // }
  52. // }
  53. // }
  54. // })
  55. console.log(wb.Sheets.Sheet1)
  56. /* 获取二进制字符串作为输出 */
  57. const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array', cellDates: true })
  58. try {
  59. // Blob 对象表示一个不可变、原始数据的类文件对象。
  60. // Blob 表示的不一定是JavaScript原生格式的数据。
  61. // File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
  62. // 返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
  63. // 设置导出文件名称
  64. FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName)
  65. } catch (e) {
  66. if (typeof console !== 'undefined') console.log(e, wbout)
  67. }
  68. return wbout
  69. }
  70. export default downTable