您的位置:首页 > 编程语言 > Java开发

读取excel,利用java反射组装实体集合

2015-12-21 10:58 471 查看
//因为java的反射,所以对文件名的要求为实体类的类名,excel第一行为实体类的属性名

private static List<Object> exportListFromExcel(Workbook workbook,

int sheetNum, String fileName) throws ClassNotFoundException,
NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
InstantiationException {
Sheet sheet = workbook.getSheetAt(sheetNum);//需要解析的当前sheet
Class<?> clazz = Class.forName("com.sujiu.hwmall.model." + fileName);// java反射出来的实体类
List<Method> methods = new ArrayList<Method>();// 用于存放反射出来的set方法
// 解析公式结果
FormulaEvaluator evaluator = workbook.getCreationHelper()
.createFormulaEvaluator();
List<Object> list = new ArrayList<Object>();
int minRowIx = sheet.getFirstRowNum();
int maxRowIx = sheet.getLastRowNum();
for (int rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) {
Object obj = clazz.newInstance();
Row row = sheet.getRow(rowIx);
short minColIx = row.getFirstCellNum();
short maxColIx = row.getLastCellNum();
for (short colIx = minColIx; colIx <= maxColIx; colIx++) {
Cell cell = row.getCell(new Integer(colIx));
CellValue cellValue = evaluator.evaluate(cell);
if (cellValue == null) {
continue;
}

if (cellValue.getCellType() == Cell.CELL_TYPE_NUMERIC) {// 数字类型,日期类型
if (DateUtil.isCellDateFormatted(cell)) {
Date field = cell.getDateCellValue();
if (rowIx == minRowIx) {// 第一行为 方法名行
String methodName = "set"
+ cellValue.getStringValue();
Method method = clazz.getDeclaredMethod(methodName,
Date.class);
methods.add(colIx, method);
} else {// 赋值操作
methods.get(colIx).invoke(obj, field);
}
} else {
Double field = cellValue.getNumberValue();
if (rowIx == minRowIx) {// 第一行为 方法名行
String methodName = "set"
+ cellValue.getStringValue();
Method method = clazz.getDeclaredMethod(methodName,
Double.class);
methods.add(colIx, method);
} else {// 赋值操作
methods.get(colIx).invoke(obj, field);
}
}
} else if (cellValue.getCellType() == Cell.CELL_TYPE_STRING) {// string类型
String field = cellValue.getStringValue();
if (rowIx == minRowIx) {// 第一行为 方法名行
String methodName = "set" + cellValue.getStringValue();
Method method = clazz.getDeclaredMethod(methodName,
String.class);
methods.add(colIx, method);
} else {// 赋值操作
methods.get(colIx).invoke(obj, field);
}
}
}
if (rowIx != minRowIx) {//不将第一行数据加载到list中去
list.add(obj);
}
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel java反射