Easyexcel(1-注解使用)
版本依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.3</version>
</dependency>
@ExcelProperty
指定当前字段对应 excel 中的那一列,可以根据名字或者 Index 去匹配,当然也可以不写。
- value:指定写入的列头,如果不指定则使用成员变量的名字作为列头;如果要设置复杂的头,可以为 value 指定多个值
- order:优先级高于 value,会根据 order 的顺序来匹配实体和 excel 中数据的顺序
- index:优先级高于 value 和 order,指定写到第几列,如果不指定则根据成员变量位置排序;默认第一个字段就是 index=0
- 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 值越小,越排在前面
注意:
- 优先级:index > order > 默认配置
- index 相当于绝对位置,下标从 0 开始
- 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
用于设置内容格式注解
- dataFormat:日期格式
- hidden:设置单元格使用此样式隐藏
- locked:设置单元格使用此样式锁定
- quotePrefix:在单元格前面增加`符号,数字或公式将以字符串形式展示
- horizontalAlignment:设置是否水平居中
- wrapped:设置文本是否应换行。将此标志设置为 true 通过在多行上显示使单元格中的所有内容可见
- verticalAlignment:设置是否垂直居中
- rotation:设置单元格中文本旋转角度。03 版本的 Excel 旋转角度区间为-90°90°,07 版本的 Excel 旋转角度区间为 0°180°
- indent:设置单元格中缩进文本的空格数
- borderLeft:设置左边框的样式
- borderRight:设置右边框样式
- borderTop:设置上边框样式
- borderBottom:设置下边框样式
- leftBorderColor:设置左边框颜色
- rightBorderColor:设置右边框颜色
- topBorderColor:设置上边框颜色
- bottomBorderColor:设置下边框颜色
- fillPatternType:设置填充类型
- fillBackgroundColor:设置背景色
- fillForegroundColor:设置前景色
- shrinkToFit:设置自动单元格自动大小
@ContentFontStyle
用于设置单元格内容字体格式的注解
- fontName:字体名称
- fontHeightInPoints:字体高度
- italic:是否斜体
- strikeout:是否设置删除水平线
- color:字体颜色
- typeOffset:偏移量
- underline:下划线
- bold:是否加粗
- charset:编码格式
@HeadStyle
用于设置标题样式
- dataFormat:日期格式
- hidden:设置单元格使用此样式隐藏
- locked:设置单元格使用此样式锁定
- quotePrefix:在单元格前面增加`符号,数字或公式将以字符串形式展示
- horizontalAlignment:设置是否水平居中
- wrapped:设置文本是否应换行。将此标志设置为 true 通过在多行上显示使单元格中的所有内容可见
- verticalAlignment:设置是否垂直居中
- rotation:设置单元格中文本旋转角度。03 版本的 Excel 旋转角度区间为-90°90°,07 版本的 Excel 旋转角度区间为 0°180°
- indent:设置单元格中缩进文本的空格数
- borderLeft:设置左边框的样式
- borderRight:设置右边框样式
- borderTop:设置上边框样式
- borderBottom:设置下边框样式
- leftBorderColor:设置左边框颜色
- rightBorderColor:设置右边框颜色
- topBorderColor:设置上边框颜色
- bottomBorderColor:设置下边框颜色
- fillPatternType:设置填充类型
- fillBackgroundColor:设置背景色
- fillForegroundColor:设置前景色
- shrinkToFit:设置自动单元格自动大小
@HeadFontStyle
用于定制标题字体格式
- fontName:设置字体名称
- fontHeightInPoints:设置字体高度
- italic:设置字体是否斜体
- strikeout:是否设置删除线
- color:设置字体颜色
- typeOffset:设置偏移量
- underline:设置下划线
- charset:设置字体编码
- bold:设置字体是否加粗
@ContentLoopMerge
用于设置合并单元格的注解,作用于字段上
- eachRow:合并列
- columnExtend:合并行
@OnceAbsoluteMerge
用于指定位置的单元格合并,作用于类上
- firstRowIndex:第一行下标
- lastRowIndex:最后一行下标
- firstColumnIndex:第一列下标
- 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-注解使用)的更多相关文章
- EasyExcel写入百万级数据到多sheet---非注解方式
EasyExcel是什么? 快速.简单避免OOM的java处理Excel工具 一.项目需求 从mongo库中查询数据,导出到excel文件中.但是动态导出的excel有多少列.列名是什么.有多少she ...
- EasyExcel无法用转换器或者注解将java字段写入为excel的数值格式
需求: 在用easyExcel导出报表时,碰到需要将数据转换为数值or货币格式的需求 过程: 1.首先采取转换器的形式 @Override public CellData convertToExcel ...
- easyexcel注解
1.@ExcelProperty 必要的一个注解,注解中有三个参数value,index分别代表列明,列序号 1.value 通过标题文本对应2.index 通过文本行号对应 2.@ColumnWit ...
- 阿里巴巴excel工具easyexcel 助你快速简单避免OOM
Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有 ...
- 阿里 EasyExcel 使用及避坑
github地址:https://github.com/alibaba/easyexcel 原本在项目中使用EasyPoi读取excel,后来为了统一技术方案,改用阿里的EasyExcel.EasyE ...
- EasyExcel导入工具(SpringMVC下使用)
easyExcel:由阿里巴巴公司开发,由github托管 github上有详细使用文档 github地址:https://github.com/alibaba/easyexcel/blob/mast ...
- 阿里 EasyExcel 7 行代码优雅地实现 Excel 文件生成&下载功能
欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...
- 基于注解的读取excel的工具包
easyexcel-wraper easyexcel-wraper是什么? 一个方便读取excel内容,且可以使用注解进行内容验证的包装工具 easyexcel-wraper有哪些功能? 在easye ...
- EasyExcel 轻松灵活读取Excel内容
写在前面 Java 后端程序员应该会遇到读取 Excel 信息到 DB 等相关需求,脑海中可能突然间想起 Apache POI 这个技术解决方案,但是当 Excel 的数据量非常大的时候,你也许发现, ...
- Excel映射到实体-easyexcel工具
来源 项目需要把Excel进行解析,并映射到对象属性,实现类似Mybatis的ORM的效果.使用的方式是自定义注解+POI,这种方式代码复杂而且不易于维护. easyexcel是阿里巴巴开源的一个框架 ...
随机推荐
- PG 实现 Dynamic SQL
CREATE OR REPLACE FUNCTION public.exec( text) RETURNS SETOF RECORD LANGUAGE 'plpgsql' AS $BODY$ BEGI ...
- 程序员出海做 AI 工具:如何用 similarweb 找到最佳流量渠道?
如题,今天给大家带来实操的一个小教程.这里先抛出个问题:"做海外流量增长,如何为产品制定营销渠道?" 分享一个方法只需要 3 步,方法如下: 找到和你产品最接近的细分 Top 竞争 ...
- 2024年1月Java项目开发指南11:axios请求与接口统一管理
axios中文网:https://www.axios-http.cn/ 安装 npm install axios 配置 在src下创建apis文件夹 创建axios.js文件 配置如下: // src ...
- Spring源码阅读(一):使用IDEA搭建Spring5.0.x源码阅读环境
说明 Spring源码阅读环境配置如下: Spring 5.x版本 Gradle 4.8.1 JDK8 IDEA2020.1 win10 搭建步骤 1. 下载Spring源码 下载地址:Github链 ...
- vue3 封装axios
1添加一个新的 http.js文件 封装axios 引入axios //引入Axios import axios from 'axios' 定义一个根地址 //视你自己的接口地址而定 var root ...
- 2020年了,Android后台保活还有戏吗?看我如何优雅的实现!
1.引言 对于移动端IM应用和消息推送应用的开发者来说,Android后台保活这件事是再熟悉不过了. 自从Android P(即Android 8.0)出现以后,Android已经从系统层面将后台保活 ...
- C Primer Plus 第6版 第六章 编程练习参考答案
编译环境VS Code+WSL GCC 源码请到文末下载 .注意:本章部分题目中用到了math.h 用gcc编译时加上-lm参数. /*第1题*************************/ #i ...
- c# set Webbowser version with WPF/Winform app
<Window x:Class="TestWPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/200 ...
- Spring Security + Redis + JWT 实现动态权限管理【前后端分离】
本篇文章环境:Spring Boot + Mybatis + Spring Security + Redis + JWT 数据库设计Web 的安全控制一般分为两个部分,一个是认证,一个是授权.认证即判 ...
- 数据库数据实时采集--Maxwell
1.Maxwell 简介 Maxwell 是一个能实时读取 MySQL 二进制日志文件binlog,并生成 Json格式的消息,作为生产者发送给 Kafka,Kinesis.RabbitMQ.Redi ...