在用POI进行Excel导入时,发觉有这种情况。
当某一行有格式的时候,POI会认为这行有数据。
用反射的方法可以排除这种数据。
public static boolean isBlankObject(Object model) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Field[] field = model.getClass().getDeclaredFields(); //获取实体类的所有属性,返回Field数组
for(int j=0 ; j<field.length ; j++){ //遍历所有属性
String name = field[j].getName(); //获取属性的名字
//System.out.println("attribute name:"+name);
name = name.substring(0,1).toUpperCase()+name.substring(1); //将属性的首字符大写,方便构造get,set方法
//String type = field[j].getGenericType().toString(); //获取属性的类型
Method m = model.getClass().getMethod("get"+name);
if(!StringUtils.isBlank((String)m.invoke(model))){
return false;
}
}
return true;
}
调用这个方法,可以将空白行去掉:
Iterator<excelLine> it = excelList.iterator();//excelList是List<excelLine>类型的Excel数据,excelLine是行的数据类型
while (it.hasNext()) {
if (isBlankObject(it.next())){
it.remove();
}
}