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

//因为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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值