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

发布于:2024-06-01 ⋅ 阅读:(102) ⋅ 点赞:(0)

一、前端代码

<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>

二、后端代码

    @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);
    }

网站公告

今日签到

点亮在社区的每一天
去签到