1. 程式人生 > 程式設計 >Springboot vue匯出功能實現程式碼

Springboot vue匯出功能實現程式碼

最近在工作遇到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匯出類easyexcelhttps://github.com/alibaba/easyexcel

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>{latestVersion}</version>
</dependency>
//這裡可以不用關閉流,流在方法結束,會自動關閉,通過配置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,WithdrawListVo.class);
       sheet1.setSheetName("sheet1");
       writer.write(list,sheet1);
   }

PostMapping,加上返回頭了。前端傳過來的context-Type 要加上multipart/form-data 型別,然後在前端傳過來的url進行拼接引數,就可以進行多引數,但是不建議引數太多

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

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。