excel数据解析成java对象
public class ExcelReadFactory {
public List<T> readExcel(Class<T> clazz, InputStream inputStream) throws Exception {
Workbook workbook = ExcelUtil.getWorkbook(inputStream);
if (workbook == null)
return null;
Sheet sheet = workbook.getSheetAt(0);
Class<?> aClass = Class.forName(clazz.getName());
Field[] fields = clazz.getDeclaredFields();
List objList = new ArrayList<>();
T obj;
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
obj = (T) aClass.newInstance();
if(row.getCell(0) == null)
continue;
for (int j = 0; j < fields.length; j++) {
Cell cell = row.getCell(j);
if(cell == null)
continue;
fields[j].setAccessible(true);
fields[j].set(obj, ExcelUtil.getCellData(cell, fields[j].getType()));
}
objList.add(obj);
}
return objList;
}
}
public class ExcelUtil {
private static Logger logger= LogManager.getLogger(ExcelUtil.class);
public static Workbook getWorkbook(InputStream inputStream){
try {
return WorkbookFactory.create(inputStream);
}catch (Exception e){
logger.error("创建workbook失败",e);
}finally {
if(inputStream !=null){
try {
inputStream.close();
} catch (IOException e) {}
}
}
return null;
}
/**
* 解析excel表格
* @param cell
* @param clazz
* @param <T>
* @return
* @throws NumberFormatException
* @throws ClassCastException
*/
public static <T> T getCellData(Cell cell,Class<T> clazz) throws NumberFormatException,ClassCastException{
T value=null;
switch (cell.getCellType()){
case Cell.CELL_TYPE_STRING:
String strValue = cell.getStringCellValue();
if(Integer.class==clazz)
Integer.valueOf(strValue);
else
value= (T) strValue;
break;
case Cell.CELL_TYPE_NUMERIC:
if(Double.class==clazz)
value = (T) Double.valueOf(cell.getNumericCellValue());
if(Integer.class==clazz)
value=(T)Integer.valueOf(((Double)cell.getNumericCellValue()).intValue());
if(String.class==clazz){
strValue=String.valueOf(cell.getNumericCellValue());
if(strValue.endsWith(".0")){
value= (T) strValue.substring(0,strValue.lastIndexOf("."));
}else {
value= (T) strValue;
}
}
break;
case Cell.CELL_TYPE_FORMULA:
value = (T) cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value= (T) cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
if(Boolean.class==clazz)
value= (T) Boolean.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
if(Byte.class==clazz)
value= (T) Byte.valueOf(cell.getErrorCellValue());
break;
default:
value=null;
}
return value;
}
}
导入的excel字段必须和java类中的字段保持一致,可以结合具体的业务需求再加以修改