Springboot vue導(dǎo)出功能實現(xiàn)代碼
最近在工作遇到vue和Springboot 實現(xiàn)導(dǎo)出功能,翻看很多資料,發(fā)現(xiàn)一些博客寫法都過時了,所以自己特此記錄下,使用版本vue2,Springboot 2x以上,chrome瀏覽器 76.0.3809.100
vue 2寫法
let blob = new Blob([res.data], { type: 'application/octer-stream' });
其中我發(fā)現(xiàn)很多博客用這樣的寫法,但是我發(fā)現(xiàn)打印res的時候沒有發(fā)現(xiàn)data這個參數(shù),總是報錯后面直接用res就好了。
正確寫法let blob = new Blob([res], { type: 'application/octer-stream' });
科普一下:axios中params和data兩者,以為他們是相同的,實則不然。 因為params是添加到url的請求字符串中的,而data是添加到請求體(body)中的,最好使用params參數(shù)
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導(dǎo)出類easyexcel https://github.com/alibaba/easyexcel
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>{latestVersion}</version> </dependency>
//這里可以不用關(guān)閉流,流在方法結(jié)束,會自動關(guān)閉,通過配置product,指定返回頭 @PostMapping(path = "/user/excelExport", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public void excelExport(WithdrawListDto withdrawListDto, HttpServletResponse response) { List<WithdrawListVo> list = withdrawService.list(withdrawListDto); ExcelWriter writer = new ExcelWriter(response.getOutputStream(), ExcelTypeEnum.XLSX, true); Sheet sheet1 = new Sheet(1, 0, WithdrawListVo.class); sheet1.setSheetName("sheet1"); writer.write(list, sheet1); }
PostMapping,加上返回頭了。前端傳過來的context-Type 要加上multipart/form-data 類型,然后在前端傳過來的url進(jìn)行拼接參數(shù),就可以進(jìn)行多參數(shù),但是不建議參數(shù)太多
例子:如/user/excelImport?account=12731564&userName=李四
@PostMapping(path = "/user/excelImport") public void excelImport(WithdrawListDto withdrawListDto,MultipartFile multipartFile) { }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Apache?Commons?Config管理配置文件核心功能使用
這篇文章主要為大家介紹了Apache?Commons?Config管理和使用配置文件核心深入探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12SpringBoot整合Docker實現(xiàn)一次構(gòu)建到處運行的操作方法
本文講解的是 SpringBoot 引入容器化技術(shù) Docker 實現(xiàn)一次構(gòu)建到處運行,包括鏡像構(gòu)建、Docker倉庫搭建使用、Docker倉庫可視化UI等內(nèi)容,需要的朋友可以參考下2022-10-10java并發(fā)編程專題(九)----(JUC)淺析CyclicBarrier
這篇文章主要介紹了java CyclicBarrier的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07詳解XML,Object,Json轉(zhuǎn)換與Xstream的使用
這篇文章主要介紹了詳解XML,Object,Json轉(zhuǎn)換與Xstream的使用的相關(guān)資料,需要的朋友可以參考下2017-02-02基于SSM+Shiro+Bootstrap實現(xiàn)用戶權(quán)限管理系統(tǒng)
這篇文章主要介紹了基于SSM+Shiro實現(xiàn)一個用戶權(quán)限管理系統(tǒng),每位用戶只可訪問指定的頁面,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定幫助,快跟隨小編一起學(xué)習(xí)吧2021-12-12