// 最好是定义一个表个通用数据,循环得到相关数据
const tableHeader = ref([
{ header: '订单', key: 'index', width: 24 },
{ header: '编号', key: 'number', width: 100 },
{ header: '序号', key: 'xh', width: 24 }
])
// 模拟表格数据
const _data = ref([
{ index: '1', number: '123456789', xh: '1' },
{ index: '2', number: '123456789', xh: '21' },
{ index: '3', number: '123456789', xh: '222' }
])
// 表格数据
const tableData = ref([])
// 前端导出,前端下载为zip包
function onExcel() {
// 1.创建一个工作簿
const wb = XLSX.utils.book_new()
// 表格标题
// 这里设置标题是怕数据没有,返回空表,连标题都没有
// 这里的权重,没有数据tableData里的高,果如tableData中没有和标题一一对应,导出的表格也会展示
// 比如:arrHeader = [a,b] 而,tableData = [{a:1,b:2,c:3}];那么表格会多一个c的列
const arrHeader = tableHeader.value.map((item) => item.header)
// 添加表格数据
_data.value.forEach((el) => {
// 根据表格标题,对应赋值
const rowData = tableHeader.value.reduce((accumulator, item, index) => {
if (item?.key) {
accumulator[item.header] = el[item.key] ?? '-'
}
return accumulator
}, {})
// 赋值所有数据
tableData.value.push(rowData)
})
// 2.创建sheet对象
const ws = XLSX.utils.json_to_sheet(tableData.value, {
header: arrHeader
})
// 调用excel 通用样式方法
excelStyle(tableHeader.value, ws)
XLSX.utils.book_append_sheet(wb, ws, '列表')
// 生成excel数据
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'array' })
// 转成Blob
var fileExcle = new Blob([wbout], { type: 'application/octet-stream' })
const zip = new JSZip()
// 添加文本
zip.file('Hello.txt', 'Hello World\n')
// 添加excel文件到压缩包
zip.file('asdfs.xlsx', fileExcle)
zip.file('asdfss.xlsx', fileExcle)
// 生成新的压缩包Blob对象
zip.generateAsync({ type: 'blob' }).then((content) => {
// 下载新的压缩包
FileSaver.saveAs(content, '批量下载.zip') // 利用file-saver保存文件
})
}