diff --git a/src/main/java/com/dsideal/base/Tools/Step5_ReaderExcel.java b/src/main/java/com/dsideal/base/Tools/Step5_ReaderExcel.java index e939ef50..e0c2cdc4 100644 --- a/src/main/java/com/dsideal/base/Tools/Step5_ReaderExcel.java +++ b/src/main/java/com/dsideal/base/Tools/Step5_ReaderExcel.java @@ -9,6 +9,10 @@ import java.io.IOException; public class Step5_ReaderExcel { public static void main(String[] args) throws IOException { String filePath = "D:\\dsWork\\YunNanDsBase\\Doc\\全省及州市县区人口与教育报告集20241023\\133个县区报告2022\\县区研究报告\\楚雄州各县市报告10\\1.楚雄市人口变化趋势对基础教育的影响分析报告\\附件2 楚雄市教育发展规模数据收集表(2024.06.13).xlsx"; + //第一个表格的宽度=23 + int firstTableWidth = 23; + //第二个表格的宽度=11 + int secondTableWidth = 11; FileInputStream fis = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fis); @@ -25,7 +29,8 @@ public class Step5_ReaderExcel { if (row == null) break; if (row.getRowNum() == 0) continue; // 跳过标题行, 本项目中有标题行 // 读取表格数据 - for (Cell cell : row) { + for (int j = 0; j < firstTableWidth; j++) { + Cell cell = row.getCell(j); // 如果单元格是公式类型 if (cell.getCellType() == CellType.FORMULA) { // 计算公式结果 @@ -42,14 +47,41 @@ public class Step5_ReaderExcel { //第二个表格 //从rowIndex开始,向下面查找,直到第一列中出现文字“自动计算招生数、在校生数”,此行的再下一行就是真正的第二个表格的开始位置 + int secondTableStartRowIndex = -1, secondTableEndRowIndex = -1; + //找到开始行 for (; rowIndex <= sheet.getLastRowNum(); rowIndex++) { Row row = sheet.getRow(rowIndex); - if (row != null && row.getCell(0) != null && row.getCell(0).toString().contains("自动计算招生数、在校生数")) { - System.out.println("rowIndex=" + rowIndex); + if (row != null && row.getCell(0) != null + && row.getCell(0).toString().contains("自动计算招生数、在校生数")) { + if (secondTableStartRowIndex == -1) + secondTableStartRowIndex = rowIndex; + } + if (secondTableStartRowIndex > 0 && row == null) { + secondTableEndRowIndex = rowIndex - 1; break; } } - break;//先调试第一个表格 + //表头有两行,需要加2 + secondTableStartRowIndex += 2; + //输出第二个表格的开始行索引和结束行索引 + System.out.println("第二个表格开始行索引=" + secondTableStartRowIndex + ",结束行索引=" + secondTableEndRowIndex); + //输出第二个表格的数据 + for (rowIndex = secondTableStartRowIndex; rowIndex <= secondTableEndRowIndex; rowIndex++) { + Row row = sheet.getRow(rowIndex); + if (row == null) break; + for (int j = 0; j < secondTableWidth; j++) { + Cell cell = row.getCell(j); + // 如果单元格是公式类型 + if (cell.getCellType() == CellType.FORMULA) { + // 计算公式结果 + cell.setCellType(CellType.NUMERIC); + } + // 打印单元格数据 + System.out.print(cell + "\t"); + } + System.out.println(); + } + break;//先调试第一个Sheet } workbook.close();