溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何實(shí)現(xiàn)Springboot vue導(dǎo)出功能

發(fā)布時(shí)間:2020-07-29 11:29:06 來源:億速云 閱讀:272 作者:小豬 欄目:編程語言

小編這次要給大家分享的是如何實(shí)現(xiàn)Springboot vue導(dǎo)出功能,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

最近在工作遇到vue和Springboot 實(shí)現(xiàn)導(dǎo)出功能,翻看很多資料,發(fā)現(xiàn)一些博客寫法都過時(shí)了,所以自己特此記錄下,使用版本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的時(shí)候沒有發(fā)現(xiàn)data這個(gè)參數(shù),總是報(bào)錯(cuò)后面直接用res就好了。
正確寫法let blob = new Blob([res], { type: 'application/octer-stream' });

科普一下:axios中params和data兩者,以為他們是相同的,實(shí)則不然。 因?yàn)閜arams是添加到url的請(qǐng)求字符串中的,而data是添加到請(qǐng)求體(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)
}
);

后臺(tái)代碼寫法 ——使用阿里巴巴的excel導(dǎo)出類easyexcel  https://github.com/alibaba/easyexcel

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>{latestVersion}</version>
</dependency>
//這里可以不用關(guān)閉流,流在方法結(jié)束,會(huì)自動(dòng)關(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&#63;account=12731564&userName=李四

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

看完這篇關(guān)于如何實(shí)現(xiàn)Springboot vue導(dǎo)出功能的文章,如果覺得文章內(nèi)容寫得不錯(cuò)的話,可以把它分享出去給更多人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI