Springboot +vue 实现导出功能

ぃ、小莉子 提交于 2019-11-28 22:12:16

最近在工作遇到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);
     }

 

 

 

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!