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