easyexcel导出文件

发布于 2020-08-10  380 次阅读


EasyExcel对poi进行了封装,功能更加强大,操作简单,也可以通过注解,拦截器等形式添加样式合并单元格等。


public static  final  void  exportSimpleExcel(HttpServletResponse response,List list,String fileName) throws IOException {
    //判断集合是否为空
    if (ObjectUtils.isEmpty(list)){
        throw new GlobalException(StatusCode.ERROR,"导出数据为空!");
    }



    //判断文件名是否为空
    if (StringUtils.isBlank(fileName)){
        //文件名默认值 default
        fileName = "default";
    }
    response.setContentType("application/octet-stream;charset=utf-8");
    response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+ "."+ ExcelTypeEnum.XLS);



    EasyExcel.write(response.getOutputStream(),list.get(0).getClass()).sheet("模板").doWrite(list);


}


/**
 * 导出(通用) 基于easyexcel
 * @param list
 * @param fileName
 * @return
 * @throws IOException
 */
public static  final  String   exportSimpleExcel(List list,String fileName) throws IOException {
    //判断集合是否为空
    if (ObjectUtils.isEmpty(list)){
        throw new GlobalException(StatusCode.ERROR,"导出数据为空!");
    }


    //判断文件名是否为空
    if (StringUtils.isBlank(fileName)){
        //文件名默认值 default
        fileName = "default";
    }




    String fileNames = TestFileUtils.getPath() + fileName + System.currentTimeMillis() + ".xlsx";

    EasyExcel.write(fileNames,list.get(0).getClass()).sheet("模板").doWrite(list);

    return  fileNames;

}


[title]下面是对拦截器的一些简单操作[/title]

在下面操作中 通过CellRangeAddress合并单元格  可以通过cell 获取行和列的索引 分别对不同单元格进行多样化的操作static  class  MergeStrategy extends AbstractMergeStrategy{
     private  Sheet sheet;
     private  List list;

     public MergeStrategy(List list){
         this.list = list;
     }


    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        this.sheet = sheet;
        if (cell.getRowIndex() ==  list.size()){
            //合并单元格 横向
            CellRangeAddress cellRangeAddress = new CellRangeAddress(list.size(), list.size(), 0, 6);
            sheet.addMergedRegionUnsafe(cellRangeAddress);

        }

    }
}

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。