excel-plus
excel-plus copied to clipboard
【question】Reader读取Excel的时候遇到null值不处理 converter
测试代码:
测试导出,模拟测试数据
@Test
public void testWriter() throws WriterException {
String fileName = "/Users/yangkai.shen/Desktop/模板.xlsx";
List<TalendModel> rows = Lists.newArrayList(new TalendModel("1","1","1","1","1",true,"1","1"),new TalendModel("1","1","1","1","1",false,"1","1"),new TalendModel("1","1","1","1","1",null,"1","1"));
Writer.create(ExcelType.XLSX).withRows(rows).headerStyle((book, style) -> {
style.setFillBackgroundColor(HSSFColor.HSSFColorPredefined.ORANGE.getIndex());
return style;
}).to(new File(fileName));
}
测试导入
@Test
public void testReader() {
String fileName = "/Users/yangkai.shen/Desktop/模板.xlsx";
List<TalendModel> talendModels = Reader.create(TalendModel.class)
.from(new File(fileName))
.sheet(0)
.start(1)
.asList();
talendModels.forEach(System.out::println);
}
实体类代码
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TalendModel {
/**
* 表中文名
*/
@ExcelColumn(title = "表中文名", index = 0)
private String tableChineseName;
/**
* 表英文名
*/
@ExcelColumn(title = "表英文名", index = 1)
private String tableEnglishName;
/**
* 字段中文名
*/
@ExcelColumn(title = "字段中文名", index = 2)
private String columnChineseName;
/**
* 字段英文名
*/
@ExcelColumn(title = "字段英文名", index = 3)
private String columnEnglishName;
/**
* 字段数据类型
*/
@ExcelColumn(title = "字段数据类型", index = 4)
private String columnDataType;
/**
* 主键
*/
@ExcelColumn(title = "主键", index = 5, converter = PrimaryKeyConverter.class)
private Boolean primaryKey;
/**
* 关联外键表
*/
@ExcelColumn(title = "关联外键表", index = 6)
private String foreignTableName;
/**
* 外键关联表字段
*/
@ExcelColumn(title = "外键关联表字段", index = 7)
private String foreignColumnName;
}
类型转换Converter代码
public class PrimaryKeyConverter implements Converter<String, Boolean> {
@Override
public Boolean stringToR(String value) {
if (StrUtil.isNotBlank(value) && StrUtil.equals("Y", value)) {
return true;
}
return false;
}
@Override
public String toString(Boolean fieldValue) {
if (fieldValue) {
return "Y";
}
return "";
}
}
遇到的问题:
Reader解析到 primaryKey 为 null 的时候不执行 PrimaryKeyConverter#stringToR(),导致 Boolean 会出现 null 值
另外还有以下一些问题:
Writer还存着一个问题,就是headerStyle样式好像并没有生效。Writer写出的时候,能否将withRows非必要条件,比如我只想导出一个模板,包含 实体类的字段信息,我直接导出实体类就行,没必要设置行数。 建议添加个class参数如下:
Writer.create(ExcelType.XLSX).class(TalendModel.class).headerStyle((book, style) -> {
style.setFillBackgroundColor(HSSFColor.HSSFColorPredefined.ORANGE.getIndex());
return style;
}).to(new File(fileName));