关于若依框架实现list数据导出到excel并实现下载(简单实现)

https://www.cnblogs.com/jdearfaust/p/16661595.html

没看源码,仅仅会用

先是在需要导出的实体类上添加若依自带的@Excel的注解,注解中主要的两个参数一个是name用于生成excel中的字段名,一个是sort用于在excel中字段的排序

@Excel(name = "车辆id",cellType = Excel.ColumnType.NUMERIC,sort = 1)
private Integer id;
 
@Excel(name = "在线状态",sort = 2)
private Boolean online;
 
 
@Excel(name = "终端条形码",sort = 3)
private String terminalBarcode;
 
@Excel(name = "终端编码",sort = 4)
private String terminalCode;

实体类标注完毕后先进行需要导出的数据的查询以及使用若依生成excel文件(文件地址在配置文件里修改)

@PostMapping("exportExcle")
 private void download(@RequestBody VehicleInfo VehicleInfo, HttpServletResponse response){<br>     //查询需要导出的数据
     List<VehicleInfo> list = vehicleManageService.exportVehicleInfo(VehicleInfo);
     //根据生成的数据生成excel表格<br>     ExcelUtil<VehicleInfo> util = new ExcelUtil<VehicleInfo>(VehicleInfo.class);<br>      //这里修改了若依自带的ExcelUtil方法让其返回文件的完整路径而是不是原先的AjaxResult
     String filePath = util.exportExcel(list,"车辆列表");<br>      //调用了通用下载方法进行文件下载
     download(filePath,response);
 }
通用文件下载方法
@PostMapping("excleDownload")
public void download(String filePath, HttpServletResponse response) {<br>     //调用通用自定义的通用下载方法
    FileUtils.download(filePath, Boolean.TRUE, response);
}
文件下载的实现
public static void download(String filePath, Boolean delete, HttpServletResponse response)
   {
       //重新设置文件名 年月日时分秒_表格名称
       String responseFileName = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(LocalDateTime.now())+"_"+filePath.substring(filePath.length()-9);
       try
       {
           File file = new File(filePath);
           //判断文件是否存在
           if (file.exists()) {
               //让浏览器认识
               response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
               response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
               //返回相应流以及文件名
               FileUtils.setAttachmentResponseHeader(response, responseFileName);
               //获取文件并输出流
               FileUtils.writeBytes(filePath, response.getOutputStream());
               //输出完毕后删除服务器端文件
               if (delete){
                   deleteFile(filePath);
               }
           }
       }
       catch (Exception e)
       {
           log.error("下载文件失败", e);
       }
   }
 
 

 

posted @ 2023-04-21 23:28  binbinx  阅读(1487)  评论(0编辑  收藏  举报