Excel的读取与导出——基于EasyExcel工具类实现
*该Excel读取仅用于简单的单行表头的数据读取
一.Excel读取
1.Excel实体字段注解
@ExcelProperty:该注解则是导入导出实体类与excel文档中标题对应字段。
@ExcelIgnore:在读、写excel的时候忽略当前字段。
@Data
public class ExcelEntity {
@ExcelProperty(value = "id")
private String id;
@ExcelProperty(value = "名字")
private String name;
@ExcelProperty(value = "性别", converter = SexConvert.class)
private Integer sex;
@ExcelProperty(value = "体重")
private Double weight;
@ExcelIgnore
private String remarks;
}
2.Excel泛型读取返回对应实体的list,通过传输Excel中sheet的名字和文件路径以及类文件。
/*
filePath: 文件路径
sheetName: excel文件下sheet名字
pojoClass: 实体类的类型
*/
public static <T> List<T> readExcelBySheetName(String filePath,String sheetName, Class<T> pojoClass){
List<T> list = new ArrayList<T>();
EasyExcel.read(filePath, pojoClass, new AnalysisEventListener<T>() {
@Override
public void invoke(T data, AnalysisContext analysisContext) {
list.add(pojoClass.cast(data));
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}).sheet(sheetName).doRead();
return list;
}
3.Excel字段转换(例如是、否转换为1、0)
在实体类上增加自定义注解converter转换器,即可将文件转换为对应的数字。
@ExcelProperty(value = "性别", converter = SexConvert.class)
private Integer sex;
是否、性别扥转换类,如果有其他文字对应数字的,可以通过if-else等方式,将文字转换为数字或者其他对应的数据类型存储到数据库中。
/**
* @description:性别转换为数字存储
*/
public class SexConvert implements Converter<Integer> {
@Override
public Class 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 convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData(integer.equals(1) ? "男" : "女");
}
}
二.Excel导出
将需要导出的文件地址、导出的实体类型字段、导出的excel文件的sheet名称,以及导出的列表数据。
// 适用于导出单个sheet,会将之前的excel中的数据以及hseet覆盖
String fileNameAddress = "D:\\opt\\upFiles\\test.xls";
List<ExcelEntity> exportList = new ArrayList<>();
exportList.add(new ExcelEntity("123", "王五", 1, 106.4, null));
exportList.add(new ExcelEntity("124", "赵四", 1, 128.4, null));
exportList.add(new ExcelEntity("125", "白云", 0, 80.8, null));
EasyExcel.write(fileNameAddress, ExcelEntity.class).sheet("自定义sheet2").doWrite(exportList);
// 多个sheet导出到一个excel文件中
try {
OutputStream out = new FileOutputStream(fileNameAddress);
ExcelWriter writer = new ExcelWriterBuilder().file(out).build();
// 写入第一个 Sheet
WriteSheet sheet1 = EasyExcel.writerSheet(0, "Sheet1").head(ExcelEntity.class).build();
writer.write(exportList, sheet1);
// 写入第二个 Sheet
WriteSheet sheet2 = EasyExcel.writerSheet(1, "Sheet2").head(ExcelEntity.class).build();
writer.write(exportList, sheet2);
writer.finish();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}