首页 > 编程语言 > 详细

SpringBoot + easyexcel + vue 下载 excel 问题

时间:2020-04-08 09:20:45      阅读:523      评论:0      收藏:0      [点我收藏+]

最近有个下载 excel 的需求,后端导出 excel 我选用了 easyexcel,但是 vue 前端老是下载不了,发现网上写的很多普遍的方法用着不行。查了下发现了可行的方法,这里写下总结。

1. 后端


不知为啥用 Post 请求下载不了,这里改成了?Get 请求

Param.java 请求参数对象

@Data
public class Param {

    private String aa;
    
    private String bb;
    
    private String cc;

}

Controller层

@GetMapping("/download")
public void download(HttpServletResponse response, Param param) throws IOException {
    // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
    String fileName = URLEncoder.encode("demo", "UTF-8");
    response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
}

/**
* 测试数据
*/
private List<DownloadData> data() {
    List<DownloadData> list = new ArrayList<DownloadData>();
    for (int i = 0; i < 10; i++) {
        DownloadData data = new DownloadData();
        data.setString("字符串" + 0);
        data.setDate(new Date());
        data.setDoubleData(0.56);
        list.add(data);
    }
    return list;
}


DownloadData.java

/**
 * 基础数据类
 *
 * @author Jiaju Zhuang
 **/
@Data
public class DownloadData {
    @ExcelProperty("字符串标题")
    private String string;
    @ExcelProperty("日期标题")
    private Date date;
    @ExcelProperty("数字标题")
    private Double doubleData;
}

2. 前端

manage.js

为下载返回 url

//数据导出
export function download(){
  return url+‘/api/dataset/excel/download‘
}

table.vue


// 引入download方法
import {download} from ‘@/api/manage‘


// 下载按钮
<a-button  icon="download" @click="downFile()">
  导出表格
</a-button>


下载方法

export default {		
		downloadExcel() {
      let url = download()
      const param = ‘?aa=‘ + this.aa + ‘&bb=‘ + this.bb + ‘&cc=‘ + this.cc
      //创建一个a标签元素
      const a = document.createElement(‘a‘)
      //给a标签设置链接属性
      a.href = url + param
      //调用点击事件
      a.click();
    }
}

3. 参考资料


springboot vue下载文件

SpringBoot + easyexcel + vue 下载 excel 问题

原文:https://www.cnblogs.com/gaohanghang/p/12657871.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!