使用Java读取Excel行:提取OrderId与Count作为后续调用输入
读取Excel中OrderId和Count字段的Java实现方案(基于Apache POI)
针对你的需求——从n×n的Excel工作表中读取OrderId和Count字段并用于后续调用,我先梳理你现有代码的问题,再给出完整的健壮实现:
现有代码的核心问题
- 变量大小写不一致:
Cell C = row1.getCell(columnIndex);后续使用小写c调用方法,会导致编译错误 - 未跳过表头:直接遍历所有行会把表头(Name/OrderId/Count/Date)也读入列表
- 单元格类型处理不当:
Count是数字类型,直接调用getStringCellValue()会抛出类型转换异常 - 列索引逻辑僵化:硬编码
columnIndex+1获取Count列,若Excel列顺序变化会失效
完整实现方案
首先确保你的项目引入了Apache POI依赖(以Maven为例):
<dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.5</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.5</version> </dependency> </dependencies>
以下是完善后的代码,支持动态查找目标列、处理多种单元格类型、跳过空行和表头:
import org.apache.poi.ss.usermodel.*; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ExcelOrderReader { public static void main(String[] args) { String excelPath = "your_file_path.xlsx"; // 替换为你的Excel文件路径 List<Map<String, Object>> orderRecords = new ArrayList<>(); try (FileInputStream fis = new FileInputStream(excelPath); Workbook workbook = WorkbookFactory.create(fis)) { Sheet targetSheet = workbook.getSheetAt(0); // 获取第一个工作表 if (targetSheet == null) { System.out.println("目标工作表为空"); return; } // 第一步:遍历表头,定位OrderId和Count的列索引 Row headerRow = targetSheet.getRow(0); int orderIdColIdx = -1; int countColIdx = -1; if (headerRow != null) { for (Cell cell : headerRow) { String headerText = cell.getStringCellValue().trim(); if ("OrderId".equals(headerText)) { orderIdColIdx = cell.getColumnIndex(); } else if ("Count".equals(headerText)) { countColIdx = cell.getColumnIndex(); } } } // 校验是否找到目标列 if (orderIdColIdx == -1 || countColIdx == -1) { System.out.println("Excel中未找到OrderId或Count列"); return; } // 第二步:遍历数据行(跳过表头行) for (int rowNum = 1; rowNum <= targetSheet.getLastRowNum(); rowNum++) { Row dataRow = targetSheet.getRow(rowNum); if (dataRow == null) continue; // 跳过空行 Map<String, Object> record = new HashMap<>(); // 读取OrderId(兼容字符串/数字类型) Cell orderIdCell = dataRow.getCell(orderIdColIdx); String orderId = getCellAsString(orderIdCell); record.put("OrderId", orderId); // 读取Count(兼容数字/字符串类型) Cell countCell = dataRow.getCell(countColIdx); Integer count = getCellAsInteger(countCell); if (count != null) { record.put("Count", count); } orderRecords.add(record); } // 输出读取结果,可直接用于后续调用 for (Map<String, Object> record : orderRecords) { System.out.printf("OrderId: %s, Count: %d%n", record.get("OrderId"), record.get("Count")); } } catch (IOException e) { e.printStackTrace(); } } // 辅助方法:将单元格值转为字符串 private static String getCellAsString(Cell cell) { if (cell == null) return ""; return switch (cell.getCellType()) { case STRING -> cell.getStringCellValue().trim(); case NUMERIC -> DateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue().toString() : String.valueOf((long) cell.getNumericCellValue()); case BOOLEAN -> String.valueOf(cell.getBooleanCellValue()); case FORMULA -> cell.getCellFormula(); default -> ""; }; } // 辅助方法:将单元格值转为整数 private static Integer getCellAsInteger(Cell cell) { if (cell == null) return null; return switch (cell.getCellType()) { case NUMERIC -> (int) cell.getNumericCellValue(); case STRING -> { try { yield Integer.parseInt(cell.getStringCellValue().trim()); } catch (NumberFormatException e) { yield null; } } default -> null; }; } }
关键特性说明
- 动态列定位:通过表头文本查找目标列索引,无需硬编码列位置,适配列顺序变化的场景
- 多类型单元格处理:兼容OrderId为数字/字符串、Count为数字/字符串的情况,避免类型转换异常
- 空行过滤:自动跳过Excel中的空行,确保读取数据的有效性
- 资源安全管理:使用
try-with-resources自动关闭Workbook和文件流,避免资源泄漏
你可以直接使用orderRecords列表作为后续调用的输入,每个元素是包含OrderId和Count的Map;如果需要更结构化的数据,也可以自定义一个OrderRecord类来存储这两个字段。
内容的提问来源于stack exchange,提问作者jlearner
相关产品推荐
相关产品推荐

