定义实体类
首先定义实体类User
,需要继承BaseRowModel
@Data
public class User extends BaseRowModel {
@ExcelProperty(value = "姓名", index = 0)
private String name;
@ExcelProperty(value = "昵称", index = 1)
private String nickName;
@ExcelProperty(value = "密码", index = 2)
private String password;
//不支持LocalDate
@ExcelProperty(value = "生日", index = 3, format = "yyyy/MM/dd")
private Date birthday;
}
日期类型不支持LocalDate,只能是Date
数据读取监听类
- 继承
AnalysisEventListene
r并要求泛型类是BaseRowModel
的子类
@Slf4j
public class ExcelListener<T extends BaseRowModel> extends AnalysisEventListener<T> {
private final List<T> rows = new ArrayList<>();
@Override
public void invoke(T object, AnalysisContext context) {
rows.add(object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
log.info("read {} rows %n", rows.size());
}
public List<T> getRows() {
return rows;
}
}
实现的比较直接,就是全部读取到List后再处理
Excel读写工具类
实现Excel数据的读取和写入
@Slf4j
public final class ExcelUtil {
/**
* 从Excel中读取文件,读取的文件是一个DTO类,该类必须继承BaseRowModel
* 具体实例参考 : MemberMarketDto.java
* 参考:https://github.com/alibaba/easyexcel
* 字符流必须支持标记,FileInputStream 不支持标记,可以使用BufferedInputStream 代替
* BufferedInputStream bis = new BufferedInputStream(new FileInputStream(...));
*/
public static <T extends BaseRowModel> List<T> readExcel(final InputStream inputStream, final Class<? extends BaseRowModel> clazz) {
if (null == inputStream) {
throw new NullPointerException("the inputStream is null!");
}
ExcelListener<T> listener = new ExcelListener<>();
// 这里因为EasyExcel-1.1.1版本的bug,所以需要选用下面这个标记已经过期的版本
ExcelReader reader = new ExcelReader(inputStream, valueOf(inputStream), null, listener);
reader.read(new com.alibaba.excel.metadata.Sheet(1, 1, clazz));
return listener.getRows();
}
public static void writeExcel(final File file, List<? extends BaseRowModel> list) {
try (OutputStream out = new FileOutputStream(file)) {
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
//写第一个sheet, 有模型映射关系
Class<? extends BaseRowModel> t = list.get(0).getClass();
Sheet sheet = new Sheet(1, 0, t);
writer.write(list, sheet);
writer.finish();
} catch (IOException e) {
log.warn("fail to write to excel file: file[{}]", file.getName(), e);
}
}
/**
* 根据输入流,判断为xls还是xlsx,该方法原本存在于easyexcel 1.1.0 的ExcelTypeEnum中。
*/
public static ExcelTypeEnum valueOf(InputStream inputStream) {
try {
FileMagic fileMagic = FileMagic.valueOf(inputStream);
if (FileMagic.OLE2.equals(fileMagic)) {
return ExcelTypeEnum.XLS;
}
if (FileMagic.OOXML.equals(fileMagic))