自定义转换器
通过自定义转换器,比如将1、0转换成男、女的实例:
public class SexConverter implements Converter<Integer> {
@Override
public Class<Integer> supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return "男".equals(cellData.getStringValue()) ? 1 : 0;
}
@Override
public CellData<String> convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData<>(integer.equals(1) ? "男" : "女");
}
}
性别属性注入SexConverter转换器:
@ExcelProperty(value = "性别", converter = SexConverter.class)
private Integer sex;
再次生成Excel,性别字段内容便显示为:男、女字样。
保留两位小数
比如体重需要保留两位小数,可通过@NumberFormat 注解实现:
@ExcelProperty(value = "体重KG")
@NumberFormat("0.##") // 会以字符串形式生成单元格,要计算的列不推荐
private BigDecimal weight;
另外一种方法是使用@ContentStyle注解:
@ContentStyle(dataFormat = 2)
private BigDecimal weight2;
这样也能达到保留两位小数的效果。
当然,也可以使用实现Converter接口的方式实现(同性别实现)。
排除指定Excel列
在很多场景下,Excel的列与实体类可能并不完全一致,这时就需要排除一些实体类的字段。
方式一:类上加注解 @ExcelIgnoreUnannotated,过滤属性没有@ExcelProperty注解的字段
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor // 一定要有无参构造方法
@ExcelIgnoreUnannotated
public class UserData {
.....
}
方式二:指定字段加@ExcelIgnore注解
@ExcelIgnore // 该字段不生成excel
private String remark;
方式三:代码指定过滤字段,通过excludeColumnFiledNames方法:
EasyExcel.write(fileName, UserData.class).sheet("学生信息表").excludeColumnFiledNames(Arrays.asList("remark")).doWrite(getData());
这种方法的好处是:同一Excel可以在调用方法时排除不同的数据列。