package poi; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class GetExcelData { public static List<Map<Integer,Object>> readFile(File file){ // excel中第幾列 : 對應的表頭 Map<Integer,String> colAndNameMap = new HashMap<>(); List<Map<Integer,Object>> resultList = new ArrayList<>(); FileInputStream fs = null; XSSFWorkbook wb = null; try { fs = new FileInputStream(file); wb = new XSSFWorkbook(fs); for(int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++){ //獲取sheet數據 XSSFSheet st = wb.getSheetAt(sheetIndex); //遍歷一個sheet中每一行 for (int rowIndex = 0; rowIndex <= st.getLastRowNum(); rowIndex++) { // 表頭:值 Map<Integer,Object> nameAndValMap = new HashMap<>(); // 獲取到一行數據 XSSFRow row = st.getRow(rowIndex); for(int cellIndex = 0; cellIndex < row.getPhysicalNumberOfCells(); cellIndex++){ if(rowIndex==0){ colAndNameMap.put(cellIndex, row.getCell(cellIndex).getStringCellValue()); }else if(!colAndNameMap.isEmpty()){ nameAndValMap.put(cellIndex, buildDate(row.getCell(cellIndex))); } } if(!nameAndValMap.isEmpty()){ resultList.add(nameAndValMap); } } } return resultList; } catch (FileNotFoundException e) { System.out.println(">>>>>>>>>> 讀取excel文件時出錯了!!!"); e.printStackTrace(); } catch (IOException e) { System.out.println(">>>>>>>>>> 讀取excel文件時出錯了!!!"); e.printStackTrace(); } catch (Exception e) { System.out.println(">>>>>>>>>> 讀取excel文件時出錯了!!!"); e.printStackTrace(); } finally{ try { wb.close(); } catch (IOException e) { e.printStackTrace(); } try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } // 將excel中時間格式字段進行處理 @SuppressWarnings("deprecation") public static String buildDate(XSSFCell cell) { String result = new String(); switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: if (cell.getCellStyle().getDataFormat() == 176) { // 處理自定義日期格式:m月d日(經過判斷單元格的格式id解決,id的值是58) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value); result = sdf.format(date); } else { double value = cell.getNumericCellValue(); CellStyle style = cell.getCellStyle(); DecimalFormat format = new DecimalFormat(); String temp = style.getDataFormatString(); // 單元格設置成常規 if (temp.equals("General")) { format.applyPattern("#"); } result = format.format(value); } break; case XSSFCell.CELL_TYPE_STRING:// String類型 result = cell.getStringCellValue(); break; default: result = ""; break; } return result; } }