/** * 讀取EXCEL模板數據 * * @param excelFilePath excel文件路徑 * @param dataRowNum 開始讀取數據的行數 * @param keyRowNum 數據字段所在行數 * @return * @throws IOException */ public static List<JSONObject> readExcelData(String excelFilePath, int dataRowNum, int keyRowNum) throws IOException { if (excelFilePath.endsWith(".xls")) version = version2003; else if (excelFilePath.endsWith(".xlsx")) version = version2007; InputStream stream = null; if (version == version2003) { stream = new FileInputStream(excelFilePath); wb = (Workbook) new HSSFWorkbook(stream); stream.close(); } else if (version == version2007) { wb = (Workbook) new XSSFWorkbook(excelFilePath); } sheet = wb.getSheetAt(0); // 行數(從0開始,相當於最后一行的索引),列數 int count_row = sheet.getLastRowNum(); int count_cell = sheet.getRow(keyRowNum).getPhysicalNumberOfCells(); List<JSONObject> list = FastList.newInstance(); JSONObject count = new JSONObject(); for (int i = 0; i < count_row; i++) { JSONObject map = new JSONObject(); for (int j = 0; j < count_cell; j++) { row = sheet.getRow(i + dataRowNum); if (isRowEmpty(row)) { continue; } if (null != row) { cell = ((org.apache.poi.ss.usermodel.Row) row).getCell(j); String k = ""; if (null != cell) { int type = cell.getCellType(); // 得到單元格數據類型 switch (type) { // 判斷數據類型 case Cell.CELL_TYPE_BLANK: k = ""; break; case Cell.CELL_TYPE_BOOLEAN: k = cell.getBooleanCellValue() + ""; break; case Cell.CELL_TYPE_ERROR: k = cell.getErrorCellValue() + ""; break; case Cell.CELL_TYPE_FORMULA: k = cell.getCellFormula(); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { k = new DataFormatter().formatRawCellContents( cell.getNumericCellValue(), 0, "yyyy-mm-dd hh:mm:ss");// 格式化日期yyyy-mm-dd hh:mm:ss } else { k = keepTwoDecimal(cell.getNumericCellValue()); // //k = cell.getNumericCellValue() + ""; // // 將科學計數法類型轉換為字符串 // /*Double double1 = new Double(k); // DecimalFormat decimalFormat = new DecimalFormat("###0");// 格式化設置 // k = decimalFormat.format(double1);*/ // //modify by zf 20191125 使用format方法解決手機號格式問題,獲取原始數據 // DecimalFormat df = new DecimalFormat("0"); // k = df.format(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: k = cell.getStringCellValue(); break; default: break; } map.put(((org.apache.poi.ss.usermodel.Row) sheet.getRow(keyRowNum)).getCell(j).getStringCellValue(), k); } } } if (map != null && map.size() != 0) { list.add(map); } } cell = null; row = null; sheet = null; wb = null; return list; }