第一步:
安装依赖:
npm install --save xlsx file-saver
这里安装了两个依赖插件,感兴趣的读者可以去点开下面的链接,查看源码:
https://github.com/SheetJS/js-xlsx
https://github.com/eligrey/FileSaver.js
第二步:
引入使用:
在你需要导出excel的vue组件里面引入,引入方式如下:
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
第三步:
在methods中加入下面的方法:
exportExcel () {
/* generate workbook object from table */
var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
/* get binary string as output */
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
} catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
return wbout
},
注意事项:
上述代码中有一个#out-table,实际上就是你要导出的table的id,命名随意,示例如下:
<el-table :data="pageData.records" style="width: 100%" v-loading="loading" id="out-table">
上述代码中还有一个sheetjs.xlsx,这个就是你导出的excel文件的名称,读者可以自行修改名称。
第四步:
通过点击事件执行exportExcel ()方法。
读者可以通过按钮点击事件,绑定上述方法,点击后就会自动导出excel文件。
导出文件后,若文件中有####或者科学计算法的数字,不要慌张,那是因为该数据的表格宽度太小了,直接鼠标调整excel中的表格宽度来查看就可以。
如有疑问可留言,喜欢的读者可关注博主——小圣贤君