引入库,需要下载
npm install xlsx
import XLSX from 'xlsx'
下载函数,调用
/**
* @description 下载excel/csv
* @param {*} dataSource 表格数据,格式为对象数组
* @param {*} columns 表头数据,格式为对象数组
* @param {*} fileName 文件名
* @param {*} fileType 下载文件类型,支持xlsx、csv
*/
download (dataSource, columns, fileName = random32key(), fileType = 'xlsx') {
if (!dataSource || !columns) {
warn('暂无数据')
return
}
if (!Array.isArray(dataSource) || !Array.isArray(columns)) {
warn('数据源格式有误')
return
}
if (dataSource.length <= 0 || columns.length <= 0) {
warn('暂无数据')
return
}
const filename = `${fileName}.${fileType}`
const data = [columns.map(column => column.title)]
dataSource.forEach(item => {
const row = []
columns.forEach(column => {
row.push(item[column.dataIndex])
})
data.push(row)
})
const wb = XLSX.utils.book_new()
const ws = XLSX.utils.aoa_to_sheet(data)
/* add worksheet to workbook */
XLSX.utils.book_append_sheet(wb, ws)
/* write workbook */
XLSX.writeFile(wb, filename, {
bookType: fileType
})
}