/** * 读取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; }
原文:https://www.cnblogs.com/yamiya/p/12333932.html