欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Springboot vue导出功能实现代码

时间:2021-12-09 18:06:48|栏目:JAVA代码|点击:

最近在工作遇到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导出类easyexcel  https://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, 0, 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) {
   }

上一篇:Spring Security拦截器引起Java CORS跨域失败的问题及解决

栏    目:JAVA代码

下一篇:Java使用多线程异步执行批量更新操作方法

本文标题:Springboot vue导出功能实现代码

本文地址:http://www.codeinn.net/misctech/186287.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有