最近在工作遇到vue和Springboot 實現導出功能,翻看很多資料,發現一些博客寫法都過時了,所以自己特此記錄下,使用版本vue2,Springboot 2x以上,chrome瀏覽器 76.0.3809.100
vue 2寫法
let blob = new Blob([res.data], { type: 'application/octer-stream' });
其中我發現很多博客用這樣的寫法,但是我發現打印res的時候沒有發現data這個參數,總是報錯後面直接用res就好了。
正確寫法let blob = new Blob([res], { type: 'application/octer-stream' });
科普一下:axios中params和data兩者,以為他們是相同的,實則不然。 因為params是添加到url的請求字符串中的,而data是添加到請求體(body)中的,最好使用params參數
import axios from 'axios' axios({ method: 'post', url: '/user/excelExport', responseType:‘blob', params } ).then(res => { const link = document.createElement('a') let blob = new Blob([res], { type: 'application/octer-stream' }); link.style.display = 'none' link.href = URL.createObjectURL(blob); link.setAttribute('download', fileName + '.xlsx'); document.body.appendChild(link); link.click(); document.body.removeChild(link); } ).catch(err => { console.log(err) } );
後臺代碼寫法 ――使用阿里巴巴的excel導出類easyexcel https://github.com/alibaba/easyexcel
//這裡可以不用關閉流,流在方法結束,會自動關閉,通過配置product,指定返回頭 @PostMapping(path = "/user/excelExport", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public void excelExport(WithdrawListDto withdrawListDto, HttpServletResponse response) { List
[e36605 ] Springboot vue導出功能實現代碼已經有482次圍觀