Java工具类03Excel读取为Map
//参考 https://www.jianshu.com/p/2ba3c0bd3eb6
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.ArrayList; 6 import java.util.HashMap; 7 import java.util.LinkedHashMap; 8 import java.util.List; 9 import java.util.Map; 10 11 import org.apache.poi.ss.usermodel.Cell; 12 import org.apache.poi.ss.usermodel.CellType; 13 import org.apache.poi.ss.usermodel.Row; 14 import org.apache.poi.ss.usermodel.Sheet; 15 import org.apache.poi.ss.usermodel.Workbook; 16 import org.apache.poi.ss.usermodel.WorkbookFactory; 17 19 /** 20 * ExcelToMapUtils 非反射读取 map 21 */ 22 public class ExcelToMapUtils { 23 24 public static List<Map<String, Object>> importExcel(String filepath, int index) { 25 List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); 26 Workbook workbook = null; 27 try { 28 workbook = WorkbookFactory.create(new FileInputStream(filepath)); 29 Sheet sheet = workbook.getSheetAt(index);//可根据index,sheetName等 30 Row row = sheet.getRow(0); //表头行 31 List<String> keys = new ArrayList<String>(); 32 for (int i = 0; i < row.getLastCellNum(); i++) { 33 Cell cell = row.getCell(i); 34 keys.add(String.valueOf(getValue(cell))); //取表头行的每一个元素,组装keys集合 35 } 36 //从第二行开始循环行 37 for (int i = 1; i <= sheet.getLastRowNum(); i++) { 38 Row currentRow = sheet.getRow(i); 39 Map<String, Object> map = new LinkedHashMap<String, Object>(); 40 //循环cell列 41 for (int j = 0; j < currentRow.getLastCellNum(); j++) { 42 map.put(keys.get(j), getValue(currentRow.getCell(j))); //组装Map 43 } 44 mapList.add(map); //组装List<Map> 45 } 46 } catch (Exception e) { 47 e.printStackTrace(); 48 throw new RuntimeException("excel解析出错"); 49 } finally { 50 try { 51 if (workbook != null) { 52 workbook.close(); 53 } 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } 57 } 58 return mapList; 59 } 60 61 private static Object getValue(Cell cell) { 62 if(cell==null) { 63 return ""; 64 } 65 if (cell.getCellTypeEnum() == CellType.BOOLEAN) { 66 return cell.getBooleanCellValue(); 67 } else if (cell.getCellTypeEnum() == CellType.NUMERIC) { 68 return cell.getNumericCellValue(); 69 } else { 70 return String.valueOf(cell.getStringCellValue()); 71 } 72 }73 }