vue使用asiox 下载后端返回的excel数据流

一、前端代码

javascript 复制代码
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button style="color: brown" @click="exportExcel">excel导出</button>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  methods: {
    exportExcel() {
      //请求
      console.log("test");
      axios
        .post("/api/export", {}, { responseType: "blob" })
        .then((res) => {
          //请求成功,触发then中的函数
          console.log(res);
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });

          // 获取 获取响应头 heads 中的 filename 文件名
          let temp = res.headers["content-disposition"]
            .split(";")[1]
            .split("filename=")[1];
          // 把 %E9%AB%98%E6%84%8F%E5%90%91%E5%AD%A6%E5%91%98303.xlsx 转化成文字
          var fileName = decodeURIComponent(temp);
          //创建一个 a 标签
          const link = document.createElement("a");
          //不显示a标签
          link.style.display = "none";
          // 给a 标签的href属性赋值
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", fileName);
          //把a标签插入页面中
          document.body.appendChild(link);
          link.click();
          //点击之后移除a标签
          document.body.removeChild(link);
        })
        .catch((error) =>
          //请求失败,触发catch中的函数 可省略
          console.log(error)
        );
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

二、后端代码

java 复制代码
    @PostMapping("/export")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("交付对象及机构信息关系表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //自行编写查询数据库数据
        List<DataOrganizationDrugRelationExport> list = Lists.newArrayList();
        EasyExcel.write(response.getOutputStream(), DataOrganizationDrugRelationExport.class).head(DataOrganizationDrugRelationHeader.class).sheet("结果").doWrite(list);
    }
相关推荐
崔庆才丨静觅4 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60615 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了5 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅5 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅5 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅6 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅6 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊6 小时前
jwt介绍
前端
爱敲代码的小鱼6 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax