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'
  })
}

 

posted @   土豆哥  阅读(884)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2020-09-22 js 数组移除时索引会发生变化造成部分无法删除
2020-09-22 layui 表格添加删除行
点击右上角即可分享
微信分享提示