利用ExcelJS写入Excel文件(2)
参考文档
https://zhuanlan.zhihu.com/p/426838654
效果
代码
<template>
<div class="test">
<button @click="download">点击下载excel</button>
</div>
</template>
<script>
import Excel from 'exceljs'
import FileSaver from 'file-saver'
export default {
methods: {
async download() {
const workbook = new Excel.Workbook()
// 不适用
// workbook.xlsx.writeFile('aaa.xlsx')
workbook.creator = 'test123'
workbook.created = new Date()
const worksheet = workbook.addWorksheet('汇总')
worksheet.addRow(['姓名', '年龄', '地址'])
worksheet.addRow(['zs', 30, 'dg'])
worksheet.addRow(['ls', 17, 'gz'])
const EXCEL_TYPE =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
// excelJs 官方文档上面的 写入文件方法只能通过node服务端使用,浏览器却不能使用writeFile()但是可以使用writeBuffer();
// 需要通过 workbook.xlsx.writeBuffer() 将 buffer转为blob 配合 file-saver导出文件
workbook.xlsx.writeBuffer().then((data) => {
const blob = new Blob([data], { type: EXCEL_TYPE })
FileSaver.saveAs(blob, 'download.xlsx')
})
},
},
}
</script>
<style scoped></style>