SpringBoot整合EasyPoi实现导出功能(1)

一、项目描述

最近在做导出的功能,之前用的是poi的方式,由于设置格式过于复杂,现在用easyPoi的封装的形式更加的方便了。

二、具体实现

(1)导入Maven

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
  • 1.easypoi 父包--作用大家都懂得
  • 2.easypoi-annotation 基础注解包,作用与实体对象上,拆分后方便maven多工程的依赖管理
  • 3.easypoi-base 导入导出的工具包,可以完成Excel导出,导入,Word的导出,Excel的导出功能
  • 4.easypoi-web 耦合了spring-mvc 基于AbstractView,极大的简化spring-mvc下的导出功能
  • 5.sax 导入使用xercesImpl这个包(这个包可能造成奇怪的问题哈),word导出使用poi-scratchpad,都作为可选包了

 (2) 注解

easyPoi 起因就是Excel的导入导出,最初的模板是实体和Excel的对应。model-row,filed-col这样利用注解我们就可以很容易做Excel导入导出

(a) @ExcelTarget

这个注解是作用在实体上面的,一般和ID进行搭配使用

(b)@Excel

这个是必须使用的注解,如果需求简单只使用这一个注解也是可以的,涵盖了常用的Excel需求,需要大家熟悉这个功能,主要分为基础,图片处理,时间处理,合并处理几块,name_id是上面讲的id用法,这里就不累言了

(c)其他的注解主要看官方吧

EasyPoi官方文档

(3)demo实现导出

(a) 创建实体类

@Data
@ExcelTarget("users") //必须要实现序列化
public class User implements Serializable {
    @Excel(name = "编号")
    private String id;
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄",orderNum="1",suffix = "元")
    private Integer age;
    @Excel(name = "生日",width = 35.0,format = "yyyy-MM-dd HH:mm:ss")
    private  Date bir;
    @ExcelIgnore
    private List<String> hobby;
    @Excel(name = "爱好",width = 20.0,orderNum = "5")
    private String hobbys;
    @Excel(name = "头像",width = 20,type = 2)
    private String photo;

    public String getHobbys() {
        StringBuilder sb = new StringBuilder();
        hobby.forEach(e->{
            sb.append(e).append("、");
        });
        return sb.toString();
    }
}

(b)测试

public class TestPoi {
    //查询所有记录 模拟数据库
    public List<User> getUsers(){
        List<User> users = new ArrayList<>();
        for (int i = 0; i <5 ; i++) {
            User user = new User();
            user.setId(String.valueOf(i));
            user.setAge(10+i);
            user.setName("小黄"+i);
            user.setBir(new Date());
            user.setHobby(Arrays.asList("烫头,抽烟"));
            users.add(user);
        }
        return users;
    }
    //导出Excel
    @Test
    public void testExport(HttpServletResponse response) throws IOException {
        //获取数据
        List<User> users = getUsers();
        //导出Excel
        //参数1、exportParams 导出配置对象, 参数2导出的类型,参数3 导出数据集合
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户信息列表", "用户信息"), User.class, users);
        //将excel写入指定位置
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream("C:\\Users\\Nastu\\Desktop\\cc.xls");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        outputStream.close();
        workbook.close();


    }
}

(c)分析

这样就可以实现导出Excel的功能了,最主要的代码就是

ExcelExportUtil.exportExcel()
    public static Workbook exportExcel(ExportParams entity, Class<?> pojoClass, Collection<?> dataSet) {
        Workbook workbook = getWorkbook(entity.getType(), dataSet.size());
        (new ExcelExportService()).createSheet(workbook, entity, pojoClass, dataSet);
        return workbook;
    }

这个方法有三个参数,第一个是ExportParams,这个参数就是导出配置对象,更改Excel的表头以及SheetName的名字。

第二个是pojoClass,就是class,第三个就是users表示需要导出的数据。

(4)如何导出list集合

@Excel(name="爱好",width=20.0,orderNum="5")
privateList<String>hobby;

 现在,我们不想用","和[]了

我们就可以再写一个字段,然后把刚才需要导出的那个字段忽略了,就可以了。

  @ExcelIgnore
    private List<String> hobby;
    @Excel(name = "爱好",width = 20.0,orderNum = "5")
    private String hobbys;
    public String getHobbys() {
        StringBuilder sb = new StringBuilder();
        hobby.forEach(e->{
            sb.append(e).append("、");
        });
        return sb.toString();
    }

 (5)导出含有对象的

(a)一对一的时候,用ExcelEntity注解

(b)一对多,  用ExcelCollection注解

(6)导出含有图片的

    @Excel(name = "头像",width = 20,type = 2)
    private String photo;

数据库中存储的一般是路径信息,然后返回即可。

(7)项目中的用法

    @ApiOperation(value = "导出Excel")
    @RequestMapping(value = "/export", method = RequestMethod.POST, produces = "application/octet-stream")
    @SysLog("'导出Excel:'.concat(#params.map[" + NormalExcelConstants.FILE_NAME + "]?:'')")
    @PreAuth("hasPermit('{}export')")
    default void exportExcel(@RequestBody @Validated PageParams<PageDTO> params, HttpServletRequest request, HttpServletResponse response,) {
        IPage<Entity> page = params.getPage();
        ExportParams exportParams = getExportParams(params, page);
        Map<String, Object> map = new HashMap<>(5);
        map.put(NormalExcelConstants.DATA_LIST, page.getRecords());
        map.put(NormalExcelConstants.CLASS, getEntityClass());
        map.put(NormalExcelConstants.PARAMS, exportParams);
        String fileName = params.getMap().getOrDefault(NormalExcelConstants.FILE_NAME, "临时文件");
        map.put(NormalExcelConstants.FILE_NAME, fileName);
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    /**
     * 构建导出参数
     *
     * @param params 分页参数
     * @param page
     * @return
     */
    default ExportParams getExportParams(PageParams<PageDTO> params, IPage<Entity> page) {
        query(params, page, params.getSize() == -1 ? Convert.toLong(Integer.MAX_VALUE) : params.getSize());

        String title = params.getMap().get("title");
        String type = params.getMap().getOrDefault("type", ExcelType.XSSF.name());
        String sheetName = params.getMap().getOrDefault("sheetName", "SheetName");

        ExcelType excelType = ExcelType.XSSF.name().equals(type) ? ExcelType.XSSF : ExcelType.HSSF;
        return new ExportParams(title, sheetName, excelType);
    }

(8)预览

    /**
     * 预览Excel
     *
     * @param params 预览参数
     * @return
     */
    @ApiOperation(value = "预览Excel")
    @SysLog("'预览Excel:' + (#params.map[" + NormalExcelConstants.FILE_NAME + "]?:'')")
    @RequestMapping(value = "/preview", method = RequestMethod.POST)
    @PreAuth("hasPermit('{}export')")
    default R<String> preview(@RequestBody @Validated PageParams<PageDTO> params) {
        IPage<Entity> page = params.getPage();
        ExportParams exportParams = getExportParams(params, page);

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, getEntityClass(), page.getRecords());
        return success(ExcelXorHtmlUtil.excelToHtml(new ExcelToHtmlParams(workbook)));
    }

猜你喜欢

转载自blog.csdn.net/MyxZxd/article/details/112243902