一、前端代码
<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);}