EasyExcel实现导出功能

1.添加依赖

        
            com.alibaba
            easyexcel
        

2.导出的数据实体继承BaseRowModel,导出字段添加@ExcelProperty注解

其中index表示展示顺序

@ApiModel(value = "ExportVo", description = "导出实体")
public class ExportVo extends BaseRowModel {

    
    @ExcelProperty(value = "param1",index = 1)
    @ApiModelProperty(name = "param1", value = "导出字段1")
    private String param1;

    @ExcelProperty(value = "param2",index = 2)
    @ApiModelProperty(name = "param2", value = "导出字段2")
    private String param2;

    ......
}

3.导出方法

/**
     * 导出数据到excel
     *
     * @param response
     * @param sheetName 表格sheet名
     * @param list 导出数据
     *
     */
    public static void export(HttpServletResponse response, String sheetName, List list){
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        try(ServletOutputStream out = response.getOutputStream()){
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(sheetName, "UTF-8")
                    + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx");

            ExcelWriter writer = EasyExcelFactory.getWriter(out);
            Sheet sheet = new Sheet(1, 0, list.get(0).getClass());
            sheet.setSheetName(sheetName);
            sheet.setAutoWidth(Boolean.TRUE);

            writer.write(list, sheet);
            writer.finish();
            out.flush();
        }catch (IOException e){
            LOG.error("Export Excel Exception!", e);
            throw new RuntimeException();
        }
    }

4.后续

目前新版本的EasyExcel,实体好像不需要继承BaseRowModel,有兴趣的关注下

你可能感兴趣的:(杂⑦杂⑧)