前端下载(导出)表格,不请求后台-----(注意:下载的当前页的数据,不是全部)

1)先在要下载的页面引入这两个文件(安装的方法 npm install xlsx --save     npm install file-saver --save)
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
2)js方法导入这三个方法
saveAs (obj, fileName) { // 当然可以自定义简单的下载文件实现方式
var tmpa = document.createElement('a')
tmpa.download = fileName || '下载'
tmpa.href = URL.createObjectURL(obj) // 绑定a标签
tmpa.click() // 模拟点击实现下载
setTimeout(function () { // 延时释放
URL.revokeObjectURL(obj) // 用URL.revokeObjectURL()来释放这个object URL
}, 100)
},
createExl (id, name) { // table的id,下载报表的名字
const vb = XLSX.utils.table_to_book(document.getElementById(id))
const vbout = XLSX.write(vb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([vbout], { type: 'application/octet-stream' }), name)
} catch (e) {
if (typeof console !== 'undefined') console.log(e, vbout)
}
},

downloadExl () {
    this.createExl('ReportTable1', '下载表格1' + '.xlsx')
}

3)html界面
<table id='ReportTable1'></table>
<button @click="downloadExl()">导出</button>

posted on 2020-06-02 11:09  每天暴走三公里  阅读(478)  评论(0编辑  收藏  举报

导航