zrlibs
2025-03-19 dad44b84ab21f9d1f860760a045015f1cab0aaec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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