阿里easyexcel是基于poi封装的一个读写excel的工具包,主要解决读大文件poi占内存大的问题,同时也提供了一些简单的excel操作API。但是网上找了下,官方说明比较少,示例都是1.*版本,2.0版本的改动还是有一些的,因此写个简单的读写示例。
引入maven依赖
com.alibaba
easyexcel
2.0.5
编写测试代码
测试思路:先定义一个List,写入本地Excel文件,再读取出来打印,如下:
@Test
public void testExcel() throws FileNotFoundException {
//定义列表
List books = Arrays.asList(new Book("isbn-1", "SpringMVC"), new Book("isbn-2", "Mybatis"));
//写入excel
ExcelUtil.writeListTo(new FileOutputStream("E:/testExcels/books_write.xlsx"),books,Book.class,Arrays.asList("isbn号","书名"));
//读取excel
List readBooks = ExcelUtil.readListFrom(new FileInputStream("E:/testExcels/books_write.xlsx"), Book.class);
System.out.println(readBooks);
}
Book对象
excelProperty是easyexcel提供的注解,用来对应excel的列
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book implements Serializable {
@ExcelProperty
private String isbn;
@ExcelProperty
private String title;
}
写入Excel
简单的写一个Sheet,使用单行的表头
public static void writeListTo(OutputStream os, List data, Class clz, List simpleHead) {
WriteSheet writeSheet = new WriteSheet();
writeSheet.setClazz(clz);
writeSheet.setNeedHead(true);
List> head = simpleHead.stream().map(a -> Arrays.asList(a)).collect(Collectors.toList());
writeSheet.setHead(head);
ExcelWriter write = EasyExcel.write(os).build();
write.write(data, writeSheet);
write.finish();
}
读取Excel
easyexcel提供了一个SyncReadListener,可以读取每行的数据放到一个List中,最后一起获取。
public static List readListFrom(InputStream is, Class clz) {
SyncReadListener tmpListener = new SyncReadListener();
ReadSheet readSheet = new ReadSheet();
readSheet.setClazz(clz);
EasyExcel.read(is).registerReadListener(tmpListener).build().read(readSheet);
return (List) tmpListener.getList();
}
扩展
上面根据Pojo对象简单的读写Excel就完成了。如果需要复杂的功能,读取的话可以定义自己的ReadListener,写入也可以定义更复杂的表头。
----------------------------------------------------------增加一个LocalDateTime转换器-------------------------------------------------------------
public class LocalDateTimeConverter implements Converter {
@Override
public Class supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(cellData.getStringValue(),dateTimeFormatter);
}
@Override
public CellData convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return new CellData(dateTimeFormatter.format(value));
}
}
继承easyExcel的Convert类,并实现其中的方法,然后修改ExcelUtil调用的地方,把这个转换器注册进去,如下图: