Vue + axios + SpringBoot 2实现导出Excel
Vue + axios + SpringBoot 2实现导出Excel
1. 前端js代码-发送Http请求
/** * 文件下载 * @param url 下载地址 * @param fileName 文件名称 * @param params 参数 */ downloadFile: function (url, params) { params = params || {} let httpService = axios.create({ timeout: 300000, // 请求超时时间 headers: { 'Cache-Control': 'no-cache' } }) return httpService({ method: 'POST', url: url, data: params, responseType: 'blob' }).then(res => { return res.data }) }, /** *文件上传 * @param url 上传地址 * @param file 文件对象 target.files <input type='file'> 的文件对象 * @param params 参数可以添加fileName ,type等等 * @returns {Promise<AxiosResponse | never>} */ uploadFile: function (url, file, params) { const formData = new FormData() params = params || {} Object.keys(params).map(key => { formData.append(key, params[key]) }) formData.append('type', params['type'] || 'ReadExcel') formData.append(params['fileName'] || 'file', file) let httpService = axios.create({ timeout: 300000, // 请求超时时间 headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'multipart/form-data' } }) return httpService.post( url, formData).then(res => { return res.data }) }
2. 前端js代码-处理后端返回的流数据(通用处理二进制文件的方法,而不仅仅针对Excel)
/** @resData 后端响应的流数据 @fileName 文件名称 如果后端设置的是xls/xlsx与后端文件后缀一致。 **/ function dealDownLoadData(resData,fileName){ try { let blob ; if(resData instanceof Blob){ blob = resData; }else{ blob = new Blob([resData], { type: resData.type}); } if (!!window.ActiveXObject || "ActiveXObject" in window) { //IE浏览器 //navigator.msSaveBlob(blob, fileName); //只有保存按钮 navigator.msSaveOrOpenBlob(blob, fileName); //有保存和打开按钮 }else{ var linkElement = document.createElement('a'); var url = window.URL.createObjectURL(blob); linkElement.setAttribute('href', url); linkElement.setAttribute("download", fileName); var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); linkElement.dispatchEvent(clickEvent); } } catch (ex) { console.log(ex); } }
3.导出Excel
/** * 导出Excel * @param request * @return * @throws Exception */ @RequestMapping(value = "/xxx") public ResponseEntity<Resource> downloadFileApi() throws Exception { //Excel场景一:直接创建,然后编辑内容 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); //Excel场景二:读取模板,然后在模板中编辑内容 POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream("/template.xls")); hssfWorkbook = new HSSFWorkbook(poifsFileSystem); //写到输出流中 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); hssfWorkbook.write(outputStream); //文件名称:注意:这里的后缀名称必须是xls或 xlsx,不然不能识别为excel String fileName = "xxx.xls"; //返回 ByteArrayInputStream is = new ByteArrayInputStream(outputStream.toByteArray()); //调用通用下载文件方法 return this.downloadFile(is, fileName); }
/** * 通用的下载方法,可以下载任何类型文件 * @param is * @param fileName * @return * @throws IOException */ public ResponseEntity<Resource> downloadFile(InputStream is,String fileName) throws IOException{ HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add("charset", "utf-8"); //设置下载文件名 headers.add("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""); Resource resource = new InputStreamResource(is); return ResponseEntity.ok() .headers(headers) //根据文件名称确定文件类型。 .contentType(MediaType.parseMediaType(HttpKit.getMimeType(fileName))) .body(resource); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2021-10-11 echarts setoption组件作用
2021-10-11 Echarts 常用API之action行为
2021-10-11 使用echarts在地图中使用dispatchAction
2020-10-11 App的埋点测试