简单实现分享,不需要做成插件,毕竟是纯工具随用随调,无需初始化,不过优化提炼下,当然可以做为ExcelKit存在。
先来个调用示例:
pom.xml引入poi依赖包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
String[] fields = {"field_A","field_B"}; List<Map> list = ExcelUtil.readExcel(filePath, fields);//map{field_A:v_A,field_B:v_B} //或者下面 //List<Map> list = ExcelUtil.readExcel(file, fields);//直接从UploadFile中取得file一行代码搞定数据读取
public static List<Map> readExcel(File file, String[] fields) throws IOException { return readExcel(new FileInputStream(file), fields); } public static List<Map> readExcel(String fPath, String[] fields) throws IOException { List<Map> list = null; try { list = readExcel(new FileInputStream(fPath), fields);//2007 - } catch (OfficeXmlFileException e) { list = readExcelPlus(new FileInputStream(fPath), fields);//2007 + } return list; }
/** * excel读取2007- * @author Lxyer 2016/8/1 10:32. */ private static List<Map> readExcel(InputStream is, String[] fields) throws IOException,OfficeXmlFileException { List<Map> list = new ArrayList<>(); HSSFWorkbook wk = new HSSFWorkbook(is); HSSFSheet sheet = wk.getSheetAt(0); int lastRowNum = sheet.getLastRowNum(); for (int i=1; i<=lastRowNum; i++){ HSSFRow row = sheet.getRow(i); Map map = new HashMap(); short cellNum = row.getLastCellNum(); for (int j=0; j<cellNum && j<fields.length; j++){ HSSFCell cell = row.getCell(j); if (cell == null){ map.put(fields[j], ""); continue; } int cellType = cell.getCellType(); if (cellType == 0){ map.put(fields[j], (long)cell.getNumericCellValue()+""); }else { map.put(fields[j], cell.getStringCellValue()); } } list.add(map); } return list; }
/** * excel读取 2007+ * @author Lxyer 2016/8/1 10:32. */ private static List<Map> readExcelPlus(InputStream is, String[] fields) throws IOException { List<Map> list = new ArrayList<>(); XSSFWorkbook wk = new XSSFWorkbook(is); XSSFSheet sheet = wk.getSheetAt(0); int lastRowNum = sheet.getLastRowNum(); for (int i=1; i<=lastRowNum; i++){ XSSFRow row = sheet.getRow(i); Map map = new HashMap(); short cellNum = row.getLastCellNum(); for (int j=0; j<cellNum && j<fields.length; j++){ XSSFCell cell = row.getCell(j); if (cell == null){ map.put(fields[j], ""); continue; } int cellType = cell.getCellType(); if (cellType == 0){ map.put(fields[j], (long)cell.getNumericCellValue()+""); }else { map.put(fields[j], cell.getStringCellValue()); } } list.add(map); } return list; }
另外:
Excel导出支持多sheet,传送 有疑问询问jf俱乐部群
依赖poi实现的 导出,支持多sheet ,支持导出list<bean> list<Map> 写的比较糙,有相关需求的随便看看,参考着自己个儿改改用