导出excel文件是开发中常见的需求
常见的做法一般是直接通过请求接口响应对象HttpServletResponse把文件输出
我们可以使用原生的poi工具类操作.也可以使用easypoi.easyexcel等基于poi二次封装的工具处理
下面是代码
@Overridepublic void export(AuctionRequest request, HttpServletResponse response) throws IOException {Map<String, Object> queryMap = Maps.newHashMap(BeanConvertUtils.beanToMap(request));List<Auction> auctions = auctionManager.listAuctions(queryMap);if (CollectionUtils.isEmpty(auctions)) {throw new AuctionException("当前数据为空");}List<AuctionDataExportModel> auctionExportModels = auctions.stream().map(item -> {AuctionDataExportModel auctionExportModel = new AuctionDataExportModel();auctionExportModel.setAuCode(item.getAuCode());auctionExportModel.setAuTitle(item.getAuTitle());return auctionExportModel;}).collect(Collectors.toList());response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setHeader("Access-Control-Allow-Origin", "*");response.setCharacterEncoding("utf-8");String fileName = URLEncoder.encode("导出", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + System.currentTimeMillis() + ".xlsx");EasyExcel.write(response.getOutputStream(), AuctionDataExportModel.class).sheet("数据区").doWrite(auctionExportModels);}
这样操作乍一看没啥问题.但是我这边前端同事是使用的axios发送的请求,必须指定响应类型为 ‘arraybuffer’ 或者 ‘blob’.
axios({method: 'post',url: '/export',responseType: 'arraybuffer',
}).then(res => {})
正常下载是没有问题的,一旦代码报错.因为指定了响应类型.就拿不到返回的错误信息了.
于是采用了成功的时候后端直接把文件上传到s3服务器,然后把文件地址返给前端.出错的时候把错误信息返给前端,就解决了上述的问题
上代码
@Overridepublic String export(AuctionRequest request) {Map<String, Object> queryMap = Maps.newHashMap(BeanConvertUtils.beanToMap(request));List<Auction> auctions = auctionManager.listAuctions(queryMap);if (CollectionUtils.isEmpty(auctions)) {throw new AuctionException("当前数据为空");}List<AuctionDataExportModel> auctionExportModels = auctions.stream().map(item -> {AuctionDataExportModel auctionExportModel = new AuctionDataExportModel();auctionExportModel.setAuCode(item.getAuCode());auctionExportModel.setAuTitle(item.getAuTitle());return auctionExportModel;}).collect(Collectors.toList());ByteArrayOutputStream bos = new ByteArrayOutputStream();EasyExcel.write(bos, AuctionDataExportModel.class).sheet("数据区").doWrite(auctionExportModels);byte[] binary = bos.toByteArray();InputStream inputStream = new ByteArrayInputStream(binary);String excelName = "导出" + IdWorker.getMillisecond() + ".xls";String returnFilePath = CommonsConstants.STORE_AUCTION_SYNC_EXCEL + excelName;PutObjectResult putObjectResult = s3Util.uploadFile(inputStream, "xls", returnFilePath);org.wildfly.common.Assert.assertNotNull(putObjectResult);return returnFilePath;}
我这里是传到s3服务器,其他的文件服务器(minio.七牛云)也都提供类似的上传api.按需替换就好了.