import ExcelJS from 'exceljs' class Excel { async exportExcel(options) { const { datas, name, columns, sheetName = 'Sheet1', frozenColumnId = 0, } = options const workbook = new ExcelJS.Workbook() workbook.creator = 'mobox' workbook.created = new Date() this.worksheet = workbook.addWorksheet(sheetName) this.headerRowId = 1 this.worksheet.columns = columns this.worksheet.addRows(datas) this.frozenColumnId = frozenColumnId this.setStyles(datas) workbook.xlsx.writeBuffer().then(data => { let blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = name + '.xlsx' document.body.appendChild(a) a.click() document.body.removeChild(a) window.URL.revokeObjectURL(a.href) }) } setStyles(datas) { this.worksheet.eachRow({ includeEmpty: true }, (row) => { row.height = 14 row.font = { size: 9 } }) this.worksheet.columns.forEach(column => column.style.alignment = Object.assign({ vertical: 'middle', horizontal: 'center', wrapText: true }, column.style.alignment || {})) for (let i = 1; i <= this.headerRowId; i++) { let row = this.worksheet.getRow(i) row.height = 18 row.eachCell(cell => { cell.style.alignment = { vertical: 'middle', horizontal: 'center', wrapText: false } cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'dddddd' }, } cell.border = { right: { style: 'thin' }, bottom: { style: 'thin' } } cell.font = { size: 9 } }) } this.worksheet.autoFilter = { from: { row: this.headerRowId, column: 1 }, to: { row: datas.length, column: this.worksheet.columns.length } } this.worksheet.views = [ { state: 'frozen', xSplit: this.frozenColumnId, ySplit: this.headerRowId } ] } } export default Excel