EasyPoi

官方文档

1.基础部分

1.1 依赖

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

1.2 注解

@Excel

作用到filed上面,是对Excel一列的一个描述
1.2.1 注解属性

image-20220505202628362

1.2.2 举例
@Data
@AllArgsConstructor
@ExcelTarget("users")
public class User {
    @Excel(name = "用户编码", width = 30)
    private Long id;
    @Excel(name = "用户名")
    private String name;
    @Excel(name = "性别")
    private String sex;
}
    public static void main(String[] args) throws IOException {
        List<User> list = new ArrayList<>();
        User user = new User(1L, "张三", "男");
        list.add(user);
        Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams("计算机一班学生", "学生"),
                User.class, list);
        FileOutputStream stream = new FileOutputStream("/aa.xls");
        sheets.write(stream);
        stream.close();
        sheets.close();
    }

@ExcelCollection

表示一个集合,主要针对一对多的导出,比如一个老师对应多个科目,科目就可以用集合表示
// 默认

@ExcelEntity

 表示一个继续深入导出的实体,但他没有太多的实际意义,只是告诉系统这个对象里面同样有导出的字段

@ExcelIgnore

和名字一样表示这个字段被忽略跳过这个导导出

@ExcelTarget

这个是作用于最外层的对象,描述这个对象的id,以便支持一个对象可以针对不同导出做出不同处理

1.3 基本用法总结

    1. 单表数据导出
//涉及注解
@ExcelTarget: 用于类上
@Excel: 用于需要导出的属性上
@ExcelIgnore: 用于不需要导出的属性上 
    1. 一对一数据导出
//此处在1的基础上进行
@ExcelEntity: 用于有外键一方中逻辑外键属性。
//注意:被引用外键的一方需要同时按照1的规则添加相应的注解
  • 一对多数据导出
//此处在1的基础上进行
@ExcelCollection: 用于逻辑外检属性上。
//子类同样需要按照1的规则进行。

2. 导出部分

2.1 导出xls

    @RequestMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        //模拟查询数据库
        List<User> users=null;
        Workbook result = ExcelExportUtil.exportExcel(
                new ExportParams("用户信息表", "用户信息"),
                User.class, users);
        //写出
        ServletOutputStream outputStream = response.getOutputStream();
        //设置请求头,解决文件名中文乱码问题
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("用户信息.xls","utf-8"));
        result.write(outputStream);
        outputStream.close();
        result.close();
    }

2.2 导出图片

// 重要步骤
@Excel(type='2')

image-20220505212657803

2.3 大数据导出

当数据量在几万甚至更多时使用

2.3.1 对应方法源码
  /**
     * @param entity
     *            表格标题属性
     * @param pojoClass
     *            Excel对象Class
     * @param dataSet
     *            Excel对象数据List
     */
    public static Workbook exportBigExcel(ExportParams entity, Class<?> pojoClass,
                                          Collection<?> dataSet) {
        ExcelBatchExportServer batachServer = ExcelBatchExportServer
            .getExcelBatchExportServer(entity, pojoClass);
        return batachServer.appendData(dataSet);
    }

    public static void closeExportBigExcel() {
        ExcelBatchExportServer batachServer = ExcelBatchExportServer.getExcelBatchExportServer(null,
            null);
        batachServer.closeExportBigExcel();
    }
2.3.2 举例
@Test
    public void bigDataExport() throws Exception {

        List<MsgClient> list = new ArrayList<MsgClient>();
        Workbook workbook = null;
        Date start = new Date();
        ExportParams params = new ExportParams("大数据测试", "测试");
        for (int i = 0; i < 1000000; i++) {  //一百万数据量
            MsgClient client = new MsgClient();
            client.setBirthday(new Date());
            client.setClientName("小明" + i);
            client.setClientPhone("18797" + i);
            client.setCreateBy("JueYue");
            client.setId("1" + i);
            client.setRemark("测试" + i);
            MsgClientGroup group = new MsgClientGroup();
            group.setGroupName("测试" + i);
            client.setGroup(group);
            list.add(client);
            //==================此处,分段写入导出===================
            if(list.size() == 10000){
                workbook = ExcelExportUtil.exportBigExcel(params, MsgClient.class, list);
                //===============清空集合,继续分段===========
                list.clear();
            }
        }
        //释放资源
        ExcelExportUtil.closeExportBigExcel();
        System.out.println(new Date().getTime() - start.getTime());
        File savefile = new File("D:/excel/");
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream("D:/excel/ExcelExportBigData.bigDataExport.xlsx");
        //写出,关流
        workbook.write(fos);
        fos.close();
    }

2.4 下拉生成

@Excel 加入 addressList 是否生成下拉的选项,默认false
目前下拉只支持replace和dict两个取值地方生成
根据对应的值生成相应的下拉,xssf下拉rowMax = 100,hssf下拉maxRow=65536,从数据第一行开始生成,使用方法也比较简单

2.5 导出样式配置

  • 源码
public interface IExcelExportStyler {
    /**
     * 列表头样式
     * @param headerColor
     * @return
     */
    public CellStyle getHeaderStyle(short headerColor);
    /**
     * 标题样式
     * @param color
     * @return
     */
    public CellStyle getTitleStyle(short color);
    /**
     * 获取样式方法
     * @param Parity
     * @param entity
     * @return
     */
    public CellStyle getStyles(boolean Parity, ExcelExportEntity entity);
}

image-20220506090954326

3. 导入部分

前提: 表单提交时,请求方式必须是post,action必须是multipart/form-data

3.1简单导入

//导入的方法有以下几个
// 入参: file(导入的文件),class(对应的pojo的class),importParams(表标题,sheet标题)
  ImportParams params = new ImportParams();
        params.getHeadRows(); //用于设置头部所占行数,默认为1
        params.setImportFields(); //用于校验xls是否符合某种格式,此处入参为一个字符串数组
        params.setSheetNum(); //上传表格需要读取的sheet 数量,默认为1
        params.setStartSheetIndex(); //开始读取的sheet位置,默认为0

image-20220506103907362

3.2 大数据读取

  • 以下方法支持大数据导入,建议 数据量在10万以上时使用。该方法不支持校验,不支持图片,不支持一对多
/**
     * Excel 通过SAX解析方法,适合大数据导入,不支持图片
     * 导入 数据源本地文件,不返回校验结果 导入 字 段类型 Integer,Long,Double,Date,String,Boolean
     * 
     * @param inputstream
     * @param pojoClass
     * @param params
     * @param handler
     */
    public static void importExcelBySax(InputStream inputstream, Class<?> pojoClass,
                                        ImportParams params, IReadHandler handler) {
        new SaxReadExcel().readExcel(inputstream, pojoClass, params, handler);
    }

学习记录

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐