Java遍历读取Excel固定的单元格实现方式
作者:小码农的
使用ApachePOI读取Excel需先添加依赖,再编写核心代码处理数据,如图所示,总结个人经验,供参考并支持脚本之家
Java遍历读取Excel固定的单元格
1、使用Apache POI读取Excel
首先引入依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </dependency>
2、核心代码
@Transactional @PreAuthorize("@ss.hasPermi('system:user:import')") @PostMapping("/importChange") public AjaxResult importChange(MultipartFile file) throws Exception { //获取表格 Workbook sheets = WorkbookFactory.create(file.getInputStream()); Sheet sheet = sheets.getSheetAt(0); int totalSubjects = 12; // 总学科数量 int startRow = 4; // 数据起始行(假设从第4行开始) // 纵向遍历每个学生 for (int rowIndex = startRow; rowIndex <= sheet.getLastRowNum(); rowIndex++) { //存放数据的实体类 BasAssessScoreDetail scoreDetail = new BasAssessScoreDetail(); //从第4行开始读取 Row row = sheet.getRow(rowIndex); Cell cellName = row.getCell(4);//获取第4行第4列的人员 Cell cellId = row.getCell(3);//获取第4行第3列的人员id String staffName = cellName.getStringCellValue(); System.out.println("人员姓名:" + staffName); String staffId = cellId.getStringCellValue(); System.out.println("人员id:" + staffId); // 遍历横向的内容 for (int itemIndex = 0; itemIndex < totalSubjects; itemIndex++) { //获取第一行 横向的内容 Row itemRow = sheet.getRow(0); //获取第一行 横向的第5列内容 Cell itemCell = itemRow.getCell(itemIndex + 5); // 学科成绩所在的单元格,加2是因为ID和姓名在前两列 String item = new DataFormatter().formatCellValue(itemCell); System.out.println("细则ID:" + item); scoreDetail.setAssId(Integer.parseInt(item)); //获取第二行 横向的内容 Row catalogRow = sheet.getRow(1); Cell catalogCell = catalogRow.getCell(itemIndex + 5); // 学科成绩所在的单元格,加2是因为ID和姓名在前两列 String catalog = new DataFormatter().formatCellValue(catalogCell); System.out.println("细则目录ID :" + catalog); scoreDetail.setCatalogId(Integer.parseInt(catalog)); //获取第三行 横向的内容 Row scoreRow = sheet.getRow(2); Cell scoreCell = scoreRow.getCell(itemIndex + 5); // 学科成绩所在的单元格,加2是因为ID和姓名在前两列 String score = new DataFormatter().formatCellValue(scoreCell); System.out.println("细则分值:" + score); scoreDetail.setRuleScore(Integer.parseInt(score)); //跟随纵向遍历的顺序 获取纵向行上所在列的内容 Row gradeRow = sheet.getRow(rowIndex); Cell gradeCell = gradeRow.getCell(itemIndex + 5); // 学科成绩所在的单元格,加2是因为ID和姓名在前两列 String grade = new DataFormatter().formatCellValue(gradeCell); System.out.println("打分分值:" + grade); scoreDetail.setScoreValue(Float.valueOf(grade)); } } return success(true); }
- Excel的表数据如图:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。