1. 程式人生 > 其它 >vue+axios 與spring boot EasyExcel實現後臺匯出excel並下載

vue+axios 與spring boot EasyExcel實現後臺匯出excel並下載

一.後端:

@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'
  })
}
為了明天能幸福,今天付出再多也不後悔。