Java/Spring中使用Apache POI读取含表头Excel文件(解决前两行读取问题)
在Java/Spring中使用Apache POI读取Excel前两行数据的实现方案
1. 添加Apache POI依赖
在pom.xml中引入POI相关依赖,同时支持xls和xlsx格式:
<dependencies> <!-- 处理xls格式Excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.5</version> </dependency> <!-- 处理xlsx格式Excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.5</version> </dependency> </dependencies>
2. 编写Spring文件上传接口
创建Controller接收上传的Excel文件,调用读取工具类完成数据读取:
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class ExcelReaderController { @PostMapping("/read-excel") public String readExcel(@RequestParam("file") MultipartFile file) { try { ExcelReaderUtil.readFirstTwoRows(file); return "前两行数据读取完成"; } catch (Exception e) { e.printStackTrace(); return "读取失败:" + e.getMessage(); } } }
3. 编写Excel读取工具类
实现读取前两行的核心逻辑,重点确保从第0行开始遍历,处理空行和不同类型的单元格:
import org.apache.poi.ss.usermodel.*; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; public class ExcelReaderUtil { public static void readFirstTwoRows(MultipartFile file) throws Exception { try (InputStream inputStream = file.getInputStream(); Workbook workbook = WorkbookFactory.create(inputStream)) { // 获取Excel的第一个Sheet(可根据实际结构调整索引) Sheet sheet = workbook.getSheetAt(0); // 遍历前两行(行索引从0开始) for (int rowNum = 0; rowNum < 2; rowNum++) { Row row = sheet.getRow(rowNum); if (row == null) { System.out.println("第" + (rowNum + 1) + "行为空行"); continue; } System.out.println("第" + (rowNum + 1) + "行数据:"); // 遍历该行所有单元格 for (Cell cell : row) { String cellValue = getCellValue(cell); System.out.print(cellValue + "\t"); } System.out.println(); } } } // 统一转换不同类型的单元格为字符串 private static String getCellValue(Cell cell) { if (cell == null) { return ""; } CellType cellType = cell.getCellType(); switch (cellType) { case STRING: return cell.getStringCellValue(); case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { return cell.getDateCellValue().toString(); } else { // 处理数字类型,避免科学计数法 return String.valueOf((long) cell.getNumericCellValue()); } case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case FORMULA: return cell.getCellFormula(); default: return ""; } } }
关键注意点
- 行索引从0开始,直接遍历
rowNum=0和rowNum=1即可获取前两行,避免因起始索引错误跳过数据。 - 处理
row == null的情况:如果某一行完全为空,sheet.getRow(rowNum)会返回null,需单独判断输出。 - 单元格类型转换:覆盖字符串、数字、日期等常见类型,保证读取数据的准确性。
内容的提问来源于stack exchange,提问作者lock
相关产品推荐
相关产品推荐

