EasyExcel-Annotation-Description-And-Usage-Guide
- Easyexcel(1-注解介绍与使用)
- Easyexcel(2-文件多Sheet、不同对象、多数据读取)
- Easyexcel(3-文件导出)
- Easyexcel(4-模板文件定义与导出)
- Easyexcel(5-自定义列宽)
- Easyexcel(6-单元格合并)
- Easyexcel(7-自定义样式)
- Easyexcel(8-通用工具类)
版本依赖
<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=0converter:指定当前字段用什么转换器,默认会自动选择。可以用来设置类型转换器,需要实现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;
}
