EasyExcel常用API注解
在EasyExcel中,我们已经可以进行导入与导出功能了,我们现在要学习的是EasyExcel中的导出是如何设置样式的。
在上一篇中我们已经可以使用EasyExcel的导出功能了,在导出的时候我们放入了一个实体类对象。这个对象就是导出的Excel的模板,正常导出,默认会使用字段名作为表头。
类上使用:
注解 | 用途 |
---|---|
@ExcelIgnoreUnannotated | 使用此注解后,属性没有添加@ExcelProperty注解则不会写入Excel |
@ColumnWidth | 设置Excel中的宽 |
@ContentRowHeight | 设置Excel中的高 |
@HeadRowHeight | 设置表头的高 |
属性上使用:
注解 | 用途 |
---|---|
@ExcelProperty | value用来自定义表头(二级表头只需要使用 {一级表头,二级表头} 来实现),index用来选择excel中的顺序(第一排为0) |
@ExcelIgnore | 表示此属性不会被写入Excel |
@DateTimeFormat | 日期格式转换 |
@ColumnWidth | 设置此属性的行宽 |
我尝试过,普通字段使用15的宽度就可以,时间字段使用25的宽度,剩下的请自行选择。
我们在使用导出时,如果遇到了时间日期等需要转换的内容,或者后台的数据需要转换数据时,可以使用 @ExcelProperty注解中的converter属性。
1.创建一个类,实现 Converter<> 接口,泛型为需要转换的类型 ,并重写其中的方法。
public class LocalDateTimeConverter implements Converter<LocalDateTime> {
@Override
public Class<LocalDateTime> supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
//将格式化后的日期转换为字符串
@Override
public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
//将LocalDateTime类型格式化
@Override
public CellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
创建了类以后,使用@ExcelProperty注解中的converter属性,进行类型转换。
@ExcelProperty(
converter = LocalDateTimeConverter.class
)
工作中一般会出现这种情况,数据库保存的数据为1,2,3,4 但是我们导出时需要转换为汉字,例如:一,二,三,四。则同样需要创建一个类。
public class LockEntranceConverter implements Converter<Integer> {
@Override
public Class supportJavaTypeKey() {
return null;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return null;
}
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return null;
}
@Override
public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
if( value == 1 ){
return new CellData("一");
}else if( value == 2 ){
return new CellData("二");
}else if( value == 3 ){
return new CellData("三");
}else if( value == 4 ){
return new CellDate("四");
}
return new CellData("");
}
}
创建了类以后,我们可以使用@ExcelProperty注解中的converter属性,进行类型转换。
注意:需要操作的字段类型要与Converter接口的泛型类型一致。
@ExcelProperty(
converter = LockEntranceConverter.class
)
EasyExcel对样式的注解比较少,其他的样式还是需要使用代码,等以后接触到了再放上来吧。