public static class ExcelListener<T> extends AnalysisEventListener<T> {
private int rowCount = 0;
private List<String> headers;
private List<Class<?>> types;
public void setRules(List<String> headers,List<Class<?>> types){
this.headers=headers;
this.types=types;
}
@Override
public void invoke(T rowData, AnalysisContext context) {
Map<Integer,Object> row= (Map<Integer, Object>) rowData;
for(int i=0;i<row.size();i++){
Object value=row.get(i);
Class<?> type=types.get(i);
String header=headers.get(i);
if(value==null){
throw new RuntimeException("解析错误:第 "+(context.readSheetHolder().getRowIndex()+1)+" 行,"+header+" 不能为空");
}else if (type==Integer.class){
if(!isIntNumeric(String.valueOf(value))) {
throw new RuntimeException("解析错误:第 " + (context.readSheetHolder().getRowIndex() + 1) + " 行," + header + " 数据类型错误");
}
}
}
rowCount++;
}
private boolean isIntNumeric(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
public int getRowCount() {
return rowCount;
}
}
使用:
public static int readExcelCnt(File file,List<String> headers,List<Class<?>> types){
ExcelListener listener = new ExcelListener();
try {
listener.setRules(headers,types);
EasyExcel.read(file, listener).sheet().doRead();
} catch (Exception e) {
throw new RuntimeException("解析Excel异常:"+e.getMessage());
}
int rowCount = listener.getRowCount();
return rowCount;
}