一.后端:
@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' }) }