Springboot +vue 实现导出功能
2021-02-04 19:17
vue 2写法
let blob = new Blob([res.data], { type: ‘application/octer-stream‘ });
正确写法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
easyexcel
//这里可以不用关闭流,流在方法结束,会自动关闭,通过配置product,指定返回头
@PostMapping(path = "/user/excelExport", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public void excelExport(WithdrawListDto withdrawListDto, HttpServletResponse response) { Listlist = 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=李四
@PostMapping(path = "/user/excelImport") public void excelImport(WithdrawListDto withdrawListDto,MultipartFile multipartFile) {
}
multipart/form-data
上一篇:python 题库|刷题
下一篇:Java常见编程错误:线程池
文章标题:Springboot +vue 实现导出功能
文章链接:http://soscw.com/index.php/essay/51031.html