实现思路:
1.获取WorkBook对象,在这里使用WorkbookFactory.create(is); // 这种方式解析Excel、2003/2007/2010都没问题;
2.对行数据进行解析
(1)首先第一行作为标题,即和基础类的字段名要保持一致。
(2)根据传入的Class创建实例
(3)利用反射,获取方法名,执行方法
Method method = cls.getDeclaredMethod(methodName,cls.getDeclaredField(title).getType()); method.invoke(obj, value);
(4)将创建的对象加入到集合
需要的jar文件:
所有的jar文件均可以在http://poi.apache.org中找到
具体实现代码细节:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; /** * 解析一个Excel表格,将其存放到一个对象集合中 * * @author jingang * */ public class ReadExcel { /** * 传入一Excel表格,创建出对应的类集合 要求: 类的字段名必须和Excel的首行的标题相同 * * @param filePath * @param cls * @return * @throws InvalidFormatException * @throws IOException * @throws InstantiationException * @throws IllegalAccessException * @throws NoSuchMethodException * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws InvocationTargetException */ public static List readExcel(String filePath, Class cls) throws InvalidFormatException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, NoSuchFieldException, IllegalArgumentException, InvocationTargetException { File excelFile = new File(filePath); FileInputStream is = new FileInputStream(excelFile); // 文件流 Workbook workbook = WorkbookFactory.create(is); // 这种方式完美支持Excel、2003/2007/2010 Sheet sheet = workbook.getSheetAt(0);// 获取工作区(只提取第一个工作区) int rowCount = sheet.getPhysicalNumberOfRows();// 文件的总行数 List<Object> objList = new ArrayList<>();// 对象的集合 Row row1 = sheet.getRow(0);// 获得首行表示,单元格的内容必须与pojo类的字段名一致 for (int i = 1; i < rowCount; i++) { // 解析每一行 Row row = sheet.getRow(i); Object obj = cls.newInstance();// 反射创建对象 for (int j = 0; j < row1.getPhysicalNumberOfCells(); j++) { String title = row1.getCell(j).getStringCellValue(); String methodName = "set" + title.substring(0, 1).toUpperCase() + title.substring(1); Cell cell = row.getCell(j); if (cell != null) { if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { int value = (int) cell.getNumericCellValue(); Method method = cls.getDeclaredMethod(methodName, cls.getDeclaredField(title).getType()); method.invoke(obj, value); } //这里可根据需要,增加对其它数据类型的判断 } else { Method method = cls.getDeclaredMethod(methodName, cls.getDeclaredField(title).getType()); method.invoke(obj, 0); } } objList.add(obj); } return objList; } }
该方法目前只是形成了一个初步的模型,仍还有许多需要改进的。譬如:
1.这里只支持了表格中的int数据类型;
2.对于方法耗时太长,可能在使用WorkbookFactory.create(is);的地方耗时太长。
希望各位有好的想法或者改进,敬请指教,多谢!