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

前端代碼

export function download() {
  return request({
    url: 'api/download',
    method: 'get',
    responseType: 'blob'
  })
}
exportExcel() {
  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)
    })
}

後臺controller代碼

@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("導出失敗");
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章