vue+axios 与spring boot EasyExcel实现后台导出excel并下载

一.后端:

@Log("导出excel")
@ApiOperation(value = "查询LawCaseCollectMain")
@GetMapping(value = "/lawCaseCollectMain/download")
public void download(HttpServletResponse response) throws IOException {
    // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
    try {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), LawCaseCollectMainDownloadData.class)
                .autoCloseStream(Boolean.FALSE)
                .sheet("模板")
                .doWrite(data());
    } catch (Exception e) {
        // 重置response
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        JsonResponse.fail().setMsg("导出失败");
    }
}

二.前端:

1.调用

 handleDown() {
      download().then((res) => {
        debugger;
        let blob = new Blob([res], { type: "application/xlsx" });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = "download.xlsx"; // 重命名文件
        link.click();
        URL.revokeObjectURL(url);
      });
    },

2.axios封装调用:

export function download() {
  return request({
    url: '/BalDetail/download',
    method: 'get',
    responseType: 'blob'
  })
}
为了明天能幸福,今天付出再多也不后悔。
原文地址:https://www.cnblogs.com/zlp520/p/15321097.html