很多后臺管理項目有導出excel表格的需求,這里只描述前端的實現方法。。
1、首先寫一個按鈕,定義一個點擊事件
<el-button
type="primary"
class="goodsindex-queryInfos-li"
size="small"
@click="send"
>導出excel
</el-button>
2、調用點擊事件,請求接口,做導出功能
send() {
let data = this.tableData; //傳入要導出的表格數據
_analysis.sendecxel(data).then(res => { //此處請求接口
// console.log(res)
const link = document.createElement("a");
const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.setAttribute("download", `${name}.xlsx`); //報表名稱可自定義
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
3、如果是封裝的接口,如下
sendecxel(data){
return new Promise((resolve, reject) => {
axios({
url: '接口路徑',
method: "post",
data: data,
responseType: 'blob' //這一行一定要加!??!
}).then((res) => {
return resolve(res)
}).catch(error => {
console.log(error)
})
})
}
這是前端要有的操作,后臺也要對接口做處理,方可實現導出excel表格