版本依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.3</version>
</dependency>

@ExcelProperty

指定当前字段对应 excel 中的那一列,可以根据名字或者 Index 去匹配,当然也可以不写。

  1. value:指定写入的列头,如果不指定则使用成员变量的名字作为列头;如果要设置复杂的头,可以为 value 指定多个值
  2. order:优先级高于 value,会根据 order 的顺序来匹配实体和 excel 中数据的顺序
  3. index:优先级高于 value 和 order,指定写到第几列,如果不指定则根据成员变量位置排序;默认第一个字段就是 index=0
  4. converter:指定当前字段用什么转换器,默认会自动选择。可以用来设置类型转换器,需要实现 Converter 接口

value

指定属性名

@Data
public class User { private Integer userId; private String name; private String phone; private String email; private Date createTime;
}
@RestController
public class TestController { @GetMapping("/test1")
public void test1(HttpServletResponse response) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("test1", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename" + fileName + ".xls"); User user = new User();
user.setUserId(123);
user.setName("as");
user.setPhone("15213");
user.setEmail("5456");
user.setCreateTime(13213L);
EasyExcel.write(response.getOutputStream(), User.class)
.sheet("test")
.doWrite(Arrays.asList(user));
} catch (Exception e) {
e.printStackTrace();
}
}
}

默认情况下,使用类的属性名作为 Excel 的列表,当然也可以使用@ExcelProperty 注解来重新指定属性名称。

@Data
public class User {
@ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机")
private String phone; @ExcelProperty(value = "邮箱")
private String email; @ExcelProperty(value = "创建时间")
private Date createTime;
}

表头合并

value 在写的时候,如果指定了多个值,会自动进行合并

@Data
public class User {
@ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = {"用户基本信息", "姓名"})
private String name; @ExcelProperty(value = {"用户基本信息", "手机"})
private String phone; @ExcelProperty(value = {"用户基本信息", "邮箱"})
private String email; @ExcelProperty(value = "创建时间")
private Date createTime;
}

index

指定位置

@ExcelProperty 注解有两个属性 index 和 order,如果不指定则按照属性在类中的排列顺序来。index 是指定该属性在 Excel 中列的下标,下标从 0 开始

@Data
public class User {
@ExcelProperty(value = "用户Id", index = 2)
private Integer userId; @ExcelProperty(value = "姓名", index = 1)
private String name; @ExcelProperty(value = "手机")
private String phone; @ExcelProperty(value = "邮箱")
private String email; @ExcelProperty(value = "创建时间")
private Date createTime;
}

@Data
public class User {
@ExcelProperty(value = "用户Id", index = 2)
private Integer userId; @ExcelProperty(value = "姓名", index = 1)
private String name; @ExcelProperty(value = "手机", index = 10)
private String phone; @ExcelProperty(value = "邮箱", index = 12)
private String email; @ExcelProperty(value = "创建时间")
private Date createTime;
}

order

指定顺序

@Data
public class User {
@ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机", order = 11)
private String phone; @ExcelProperty(value = "邮箱", order = 10)
private String email; @ExcelProperty(value = "创建时间")
private Long createTime;
}

order 的默认值为 Integer.MAX_VALUE,通过效果我们可以得出结论:order 值越小,越排在前面

注意:

  1. 优先级:index > order > 默认配置
  2. index 相当于绝对位置,下标从 0 开始
  3. order 相当于相对位置,值越小的排在越前面

convert

自定义转换器

在读写 EXCEL 时,有时候需要我们进行数据类型转换,例如我们这里的创建时间,在实体对象中是 Long 类型,但是这样直接导出到 Excel 中不太直观。我们需要转换成 yyyy-MM-dd HH:mm:ss 格式,此时我们就可以用到转换器。

public class DateTimeConverter implements Converter<Long> {

    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // 支持导入的Java类型
@Override
public Class<?> supportJavaTypeKey() {
return Long.class;
} // 支持导出的Excel类型
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
} // 转换为Java
@Override
public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return null;
} // 转换为Excel
@Override
public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
if (value == null) {
return new WriteCellData(CellDataTypeEnum.STRING, null);
}
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneId.systemDefault());
String dateStr = localDateTime.format(dateTimeFormatter);
return new WriteCellData(dateStr);
}
}
@Data
public class User {
@ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机", order = 11)
private String phone; @ExcelProperty(value = "邮箱", order = 10)
private String email; @ExcelProperty(value = "创建时间", converter = DateTimeConverter.class)
private Long createTime;
}

枚举转换

/**
* Excel 性别转换器
*/
public class GenderConverter implements Converter<Integer> {
@Override
public Class<?> supportJavaTypeKey() {
return Integer.class;
} @Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
} @Override
public Integer convertToJavaData(ReadConverterContext<?> context) {
return GenderEnum.convert(context.getReadCellData().getStringValue()).getValue();
} @Override
public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) {
return new WriteCellData<>(GenderEnum.convert(context.getValue()).getDescription());
}
}
/**
* 性别枚举
*/
@Getter
@AllArgsConstructor
public enum GenderEnum { UNKNOWN(0, "未知"), MALE(1, "男性"), FEMALE(2, "女性"); private final Integer value; private final String description; public static GenderEnum convert(Integer value) {
return Stream.of(values())
.filter(bean -> bean.value.equals(value))
.findAny()
.orElse(UNKNOWN);
} public static GenderEnum convert(String description) {
return Stream.of(values())
.filter(bean -> bean.description.equals(description))
.findAny()
.orElse(UNKNOWN);
}
}

@ExcelIgnore

默认所有字段都会和 excel 去匹配,加了这个注解会忽略该字段

@Data
public class User {
@ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机")
private String phone; @ExcelProperty(value = "邮箱")
@ExcelIgnore
private String email; @ExcelProperty(value = "创建时间", converter = DateTimeConverter.class)
@ExcelIgnore
private Long createTime;
}

@ExcelIgnoreUnannotated

不标注该注解时,默认类中所有成员变量都会参与读写,无论是否在成员变量上加了@ExcelProperty 的注解。标注该注解后,类中的成员变量如果没有标注 @ExcelProperty 注解将不会参与读写。

@ExcelIgnoreUnannotated
@Data
public class User { @ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机")
private String phone; private String email; private Long createTime;
}

@ColumnWidth

用于设置表格列的宽度

@Data
public class User { @ColumnWidth(200)
@ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机")
private String phone; @ExcelProperty(value = "邮箱")
private String email; @ExcelProperty(value = "创建时间", converter = DateTimeConverter.class)
private Long createTime;
}

@ContentRowHeight

标注在类上,指定内容行高

@Data
@ContentRowHeight(value = 50)
public class User { @ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机")
private String phone; @ExcelProperty(value = "邮箱")
private String email; @ExcelProperty(value = "创建时间", converter = DateTimeConverter.class)
private Long createTime;
}

@HeadRowHeight

标注在类上,指定列头行高

@Data
@HeadRowHeight(80)
@ContentRowHeight(value = 50)
public class User { @ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机")
private String phone; @ExcelProperty(value = "邮箱")
private String email; @ExcelProperty(value = "创建时间", converter = DateTimeConverter.class)
private Long createTime;
}

@ContentStyle

用于设置内容格式注解

  1. dataFormat:日期格式
  2. hidden:设置单元格使用此样式隐藏
  3. locked:设置单元格使用此样式锁定
  4. quotePrefix:在单元格前面增加`符号,数字或公式将以字符串形式展示
  5. horizontalAlignment:设置是否水平居中
  6. wrapped:设置文本是否应换行。将此标志设置为 true 通过在多行上显示使单元格中的所有内容可见
  7. verticalAlignment:设置是否垂直居中
  8. rotation:设置单元格中文本旋转角度。03 版本的 Excel 旋转角度区间为-90°90°,07 版本的 Excel 旋转角度区间为 0°180°
  9. indent:设置单元格中缩进文本的空格数
  10. borderLeft:设置左边框的样式
  11. borderRight:设置右边框样式
  12. borderTop:设置上边框样式
  13. borderBottom:设置下边框样式
  14. leftBorderColor:设置左边框颜色
  15. rightBorderColor:设置右边框颜色
  16. topBorderColor:设置上边框颜色
  17. bottomBorderColor:设置下边框颜色
  18. fillPatternType:设置填充类型
  19. fillBackgroundColor:设置背景色
  20. fillForegroundColor:设置前景色
  21. shrinkToFit:设置自动单元格自动大小

@ContentFontStyle

用于设置单元格内容字体格式的注解

  1. fontName:字体名称
  2. fontHeightInPoints:字体高度
  3. italic:是否斜体
  4. strikeout:是否设置删除水平线
  5. color:字体颜色
  6. typeOffset:偏移量
  7. underline:下划线
  8. bold:是否加粗
  9. charset:编码格式

@HeadStyle

用于设置标题样式

  1. dataFormat:日期格式
  2. hidden:设置单元格使用此样式隐藏
  3. locked:设置单元格使用此样式锁定
  4. quotePrefix:在单元格前面增加`符号,数字或公式将以字符串形式展示
  5. horizontalAlignment:设置是否水平居中
  6. wrapped:设置文本是否应换行。将此标志设置为 true 通过在多行上显示使单元格中的所有内容可见
  7. verticalAlignment:设置是否垂直居中
  8. rotation:设置单元格中文本旋转角度。03 版本的 Excel 旋转角度区间为-90°90°,07 版本的 Excel 旋转角度区间为 0°180°
  9. indent:设置单元格中缩进文本的空格数
  10. borderLeft:设置左边框的样式
  11. borderRight:设置右边框样式
  12. borderTop:设置上边框样式
  13. borderBottom:设置下边框样式
  14. leftBorderColor:设置左边框颜色
  15. rightBorderColor:设置右边框颜色
  16. topBorderColor:设置上边框颜色
  17. bottomBorderColor:设置下边框颜色
  18. fillPatternType:设置填充类型
  19. fillBackgroundColor:设置背景色
  20. fillForegroundColor:设置前景色
  21. shrinkToFit:设置自动单元格自动大小

@HeadFontStyle

用于定制标题字体格式

  1. fontName:设置字体名称
  2. fontHeightInPoints:设置字体高度
  3. italic:设置字体是否斜体
  4. strikeout:是否设置删除线
  5. color:设置字体颜色
  6. typeOffset:设置偏移量
  7. underline:设置下划线
  8. charset:设置字体编码
  9. bold:设置字体是否加粗

@ContentLoopMerge

用于设置合并单元格的注解,作用于字段上

  1. eachRow:合并列
  2. columnExtend:合并行

@OnceAbsoluteMerge

用于指定位置的单元格合并,作用于类上

  1. firstRowIndex:第一行下标
  2. lastRowIndex:最后一行下标
  3. firstColumnIndex:第一列下标
  4. lastColumnIndex:最后一列下标

@DateTimeFormat

日期转换,读取 Excel 文件时用 String 去接收 excel 日期格式的数据会调用这个注解。里面的 value 参照 java.text.SimpleDateFormat

@Data
public class User { @ExcelProperty(value = "用户Id")
private Integer userId; @ExcelProperty(value = "姓名")
private String name; @ExcelProperty(value = "手机")
private String phone; @ExcelProperty(value = "邮箱")
private String email; @DateTimeFormat("yyyy-MM-dd")
@ExcelProperty(value = "创建时间")
private Date createTime;
}

@NumberFormat

数字转换,用 String 去接收 excel 数字格式的数据会调用这个注解。里面的 value 参照 java.text.DecimalFormat

Easyexcel(1-注解使用)的更多相关文章

  1. EasyExcel写入百万级数据到多sheet---非注解方式

    EasyExcel是什么? 快速.简单避免OOM的java处理Excel工具 一.项目需求 从mongo库中查询数据,导出到excel文件中.但是动态导出的excel有多少列.列名是什么.有多少she ...

  2. EasyExcel无法用转换器或者注解将java字段写入为excel的数值格式

    需求: 在用easyExcel导出报表时,碰到需要将数据转换为数值or货币格式的需求 过程: 1.首先采取转换器的形式 @Override public CellData convertToExcel ...

  3. easyexcel注解

    1.@ExcelProperty 必要的一个注解,注解中有三个参数value,index分别代表列明,列序号 1.value 通过标题文本对应2.index 通过文本行号对应 2.@ColumnWit ...

  4. 阿里巴巴excel工具easyexcel 助你快速简单避免OOM

    Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有 ...

  5. 阿里 EasyExcel 使用及避坑

    github地址:https://github.com/alibaba/easyexcel 原本在项目中使用EasyPoi读取excel,后来为了统一技术方案,改用阿里的EasyExcel.EasyE ...

  6. EasyExcel导入工具(SpringMVC下使用)

    easyExcel:由阿里巴巴公司开发,由github托管 github上有详细使用文档 github地址:https://github.com/alibaba/easyexcel/blob/mast ...

  7. 阿里 EasyExcel 7 行代码优雅地实现 Excel 文件生成&下载功能

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...

  8. 基于注解的读取excel的工具包

    easyexcel-wraper easyexcel-wraper是什么? 一个方便读取excel内容,且可以使用注解进行内容验证的包装工具 easyexcel-wraper有哪些功能? 在easye ...

  9. EasyExcel 轻松灵活读取Excel内容

    写在前面 Java 后端程序员应该会遇到读取 Excel 信息到 DB 等相关需求,脑海中可能突然间想起 Apache POI 这个技术解决方案,但是当 Excel 的数据量非常大的时候,你也许发现, ...

  10. Excel映射到实体-easyexcel工具

    来源 项目需要把Excel进行解析,并映射到对象属性,实现类似Mybatis的ORM的效果.使用的方式是自定义注解+POI,这种方式代码复杂而且不易于维护. easyexcel是阿里巴巴开源的一个框架 ...

随机推荐

  1. IM开发快速入门(一):什么是IM系统?

    本文在编写时参考了博客作者"鹿呦呦"和在线课程"即时消息技术剖析与实战"的相关资料,一并表示感谢. 1.系列文章引言 IM系统看似简单(没错,很多土老板认为开发 ...

  2. JVM:java虚拟机栈

  3. 【SQL跟踪工具】SQL Profiler 跟踪器使用

    阅读目录 什么是SQL Profiler 为什么要使用SQL Profiler 如何使用SQL Profiler 什么是SQL Profiler SQL Server Profiler 是一个功能丰富 ...

  4. 第8章 LINQ 查询

    第8章 LINQ 查询 8.2 流式语法 8.2.2 使用 Lambda 表达式 常用运算符 Where() 筛选器 Order() 排序器 Select() 映射器 Take() 获取前 x 个元素 ...

  5. CPU的指令周期

    本文分享自天翼云开发者社区<CPU的指令周期>,作者:冯****怡 指令周期(Instruction Cycle) CPU中会有 存器.指令寄存器.控制器等多类单元.指令集,就是CPU中用 ...

  6. 魔乐社区体验:探索Llama 3.1模型微调之旅

    在2024年的AI领域,Meta发布的Llama 3.1模型无疑成为了研究者和开发者的新宠.我有幸通过魔乐社区提供的资源,对这一模型进行了深入的学习和实践.在这个过程中,魔乐社区的资源和支持给我留下了 ...

  7. Windows 本地虚拟磁盘

    本文介绍如何本地创建虚拟磁盘 虚拟磁盘vhdx是类似物理硬盘一样的磁盘,可以被格式化.内部添加分区,可以指定系统文件格式如NTFS.exFAT 一个vhdx文件对应一个虚拟磁盘,下面我们来操作vhdx ...

  8. tomcat切割日志(log_cut.sh)

    vim log_cut.sh #!/bin/bash #auther by wangxp #tomcat日志位置 LOG_DIR=/u01/yhpt/yhpt_cda/sdmp/logs #切割日志名 ...

  9. Flink名词介绍

    一.常用名词 1.Slot:处理槽,一般为服务器核数*4,平分服务器内存 2.Window:时间窗口 滚动窗口(Tumbling Window)将事件拆分成固定长度,窗口之间不重叠,窗口长度固定 例: ...

  10. Luogu P9180 [COCI2022-2023#5] Slastičarnica 题解 [ 蓝 ] [ 区间 dp ] [ dp 状态优化 ] [ 前缀和优化 ]

    Slastičarnica:非常好的区间 dp 题. 暴力 不难设计出暴力状态:\(dp_{q,i,j}\) 表示进行到第 \(q\) 次操作,剩下区间 \([i,j]\) 是否可行. 直到全部状态都 ...