需求:根据筛选条件,导出满足条件的.xls文件数据
分析:将筛选条件通过请求提交到后台,后台返回arrayBuffer格式的数据,前端通过new Blob解析,并通过创建隐藏的a
标签实现下载
代码
点击导出,绑定click事件
<div class="export" @click="exportExcel"><i class="iconfont icon-excel"></i>导出</div>
exportExcel () {
let me = this
const {beginDate,endDate,projectId,orderBy,status,materialId} = this.page
if (this.tableData.length > 0) {
let param = {
beginDate:beginDate ? commonFn.dateFormat(beginDate, "yyyy-MM-dd 00:00:00") : '',
endDate:endDate ? commonFn.dateFormat(endDate, "yyyy-MM-dd 23:59:59") : '',
projectId,
materialId,
status,
orderBy
}
// 向后台发送请求,返回ArrayBuffer格式的数据
this.$api.order.exportData(param)
.then(res => {
this.ab2str(res, function (str) {
me.download(res)
});
})
.catch(error => {
console.log(error)
})
} else {
this.$message({
message: '暂无数据',
type: 'warning'
});
}
},
ab2str (u, f) { //arraybuffer类型的返回值转成json
var b = new Blob([u]);
var r = new FileReader();
r.readAsText(b, 'utf-8');
r.onload = function () { if (f) f.call(null, r.result) }
},
//下载
download (data) {
if (this.isIE()) {
let excelBlob = new Blob([data])
window.navigator.msSaveOrOpenBlob(excelBlob, '订单列表.xls');
} else {
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', '订单列表.xls')
document.body.appendChild(link)
link.click()
}
},
//判断是否IE浏览器
isIE () {//判断是否IE浏览器
if (!!window.ActiveXObject || "ActiveXObject" in window) {
return true;
} else {
return false;
}
}
//axios请求:
exportData(param) { //导出excel
let me = this;
return new Promise(function (resolve, reject) {
axios.get('/gys/partner/provider/order/exportData',{
params: param,
//这个参数很重要哟
responseType: 'arraybuffer'
})
.then(res => {
me.reDirect(res, resolve)
})
.catch(error => {
reject(error)
})
})
},
网友评论