Springboot +vue 實現導出功能

最近在工做遇到vue和Springboot 實現導出功能,翻看不少資料,發現一些博客寫法都過期了,因此本身特此記錄下,使用版本vue2,Springboot 2x以上,chrome瀏覽器  76.0.3809.100前端

vue 2寫法vue

 let blob = new Blob([res.data], { type: 'application/octer-stream' });ios

 其中我發現不少博客用這樣的寫法,可是我發現打印res的時候沒有發現data這個參數,老是報錯後面直接用res就行了。

 正確寫法let blob = new Blob([res], { type: 'application/octer-stream' });git

 科普一下:axios中params和data二者,覺得他們是相同的,實則否則。 由於params是添加到url的請求字符串中的,而data是添加到請求體(body)中的,最好使用params參數github

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/easyexcelchrome

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>{latestVersion}</version>
</dependency>axios

 

//這裏能夠不用關閉流,流在方法結束,會自動關閉,經過配置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); }

 

反過來推導入,也能夠用這種方式,而且支持多參數,當加入MultipartFile 對象,SpringBoot 能夠本身識別圖片類型,不須要在PostMapping,加上返回頭了。前端傳過來的context-Type 要加上multipart/form-data 類型,而後在前端傳過來的url進行拼接參數,就能夠進行多參數,可是不建議參數太多瀏覽器

例子:如/user/excelImport?account=12731564&userName=李四app

 


@PostMapping(path = "/user/excelImport") public void excelImport(WithdrawListDto withdrawListDto,MultipartFile multipartFile) {


}

 

multipart/form-data
相關文章
相關標籤/搜索