导入的方式如果加上反射是什么样子呢?
如下:
private static List<Object> readExcel2003(FileInputStream fins, ImportParams params, String[] colunName, String[] headerName,Class clazz) throws IOException, InstantiationException, IllegalAccessException {
List<Object> lists = new ArrayList<>();
HSSFWorkbook hwb = new HSSFWorkbook(fins);
HSSFSheet sheet = hwb.getSheetAt(0);
HSSFRow row = sheet.getRow(params.getStartRows());
HSSFCell cell = row.getCell(params.getCellNum());
boolean flag = true;
int totalNum = 0;
int rowNum = 0;
if (cell == null) {
return lists;
}
for (int i = 0; i < hwb.getNumberOfSheets(); i++) {
Sheet sheetData = hwb.getSheetAt(i);
if (sheetData == null) {
continue;
}
/*统计导入的总条数,要是你的excell包含了表头,就不用加1了*/
if (sheetData.getLastRowNum() > 0) {
totalNum += sheetData.getLastRowNum();
}
rowNum = row.getPhysicalNumberOfCells();
Row rowsHeader = sheetData.getRow(0);
for (int k = 0; k < rowNum; k++) {
Cell cellData = rowsHeader.getCell(k);
if (!cellData.toString().equals(headerName[k])) {
flag = false;
}
}
if (flag) {
/*遍历行,这里j的初始值取1是因为我的表格里第一行是表头*/
for (int j = 1; j < sheetData.getPhysicalNumberOfRows(); j++) {
Cell cellData = null;
JSONObject jsonObject = new JSONObject();
for (int k = 0; k < rowNum; k++) {
Row rows = sheetData.getRow(j);
/*解析列,下标从0开始*/
cellData = rows.getCell(k);
jsonObject.put(colunName[k], cellData.toString());
if (cellData == null) {
continue;
}
}
Field[] fields = clazz.getDeclaredFields();
Object obj = clazz.newInstance();
for (Field f:fields){
Object val = TypeUtils.cast(jsonObject.get(f.getName().toString()),f.getType(),null);
f.setAccessible(true);
f.set(obj,val);
}
System.out.println(obj.toString());
lists.add(obj);
}
}
}
return lists;
}
Field[] fields = clazz.getDeclaredFields();
Object obj = clazz.newInstance();
for (Field f:fields){
Object val = TypeUtils.cast(jsonObject.get(f.getName().toString()),f.getType(),null);
f.setAccessible(true);
f.set(obj,val);
}
System.out.println(obj.toString());
lists.add(obj);
不过我觉得返回List与返回JSONArray是一样的结果。