使用hutool工具类解析合并表头示例
- 工作小总结&小工具类
- 时间:2025-07-09 12:27
- 30人已阅读
简介
凯哥获取到的excel如下图:需求分析:hutool工具类怎么读取如附件中的excel?表头是合并的.其中A到L列表头第一行和第二行是合并的。从M到BD列是分开的。我需要读取的数据从第3列开始,我需要的数据表头:A列(注意A列是第一行和第二行合并的):数据日期,N列(注意:N列第一行和第二行不合并):总。怎么处理呢?操作步骤:步骤1:依赖引入 &nbs
🔔🔔🔔好消息!好消息!🔔🔔🔔
有需要的朋友👉:联系凯哥
凯哥获取到的excel如下图:
需求分析:hutool 工具类怎么读取如附件中的excel?表头是合并的.其中A到L列表头第一行和第二行是合并的。从M到BD列是分开的。我需要读取的数据从第3列开始,我需要的数据表头:A列(注意A列是第一行和第二行合并的):数据日期,N列(注意:N列第一行和第二行不合并):总。怎么处理呢?
操作步骤:
步骤 1:依赖引入
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.38</version> </dependency>
步骤 2:处理合并表头,读取数据
核心思路:
import cn.hutool.core.io.FileUtil; import cn.hutool.poi.excel.ExcelReader; import cn.hutool.poi.excel.ExcelUtil; import org.apache.poi.ss.usermodel.CellRangeAddress; import java.io.File; import java.util.List; public class ExcelMergeReadDemo { public static void main(String[] args) { // 1. 加载Excel文件 File file = FileUtil.file("path/to/your/excel.xlsx"); // 替换为实际路径 ExcelReader reader = ExcelUtil.getReader(file); try { // 2. 读取表头的两行(第1行索引0,第2行索引1) List<Object> headerRow0 = reader.readRow(0); // 表头第一行(合并区域的“主”单元格) List<Object> headerRow1 = reader.readRow(1); // 表头第二行(可能包含空值,需填充) // 3. 处理合并单元格:将第1行的合并值填充到第2行对应列 List<CellRangeAddress> mergedRegions = reader.getSheet().getMergedRegions(); for (CellRangeAddress region : mergedRegions) { int firstRow = region.getFirstRow(); int lastRow = region.getLastRow(); // 仅处理表头的合并(第1行和第2行,索引0和1) if (firstRow == 0 && lastRow == 1) { int firstCol = region.getFirstColumn(); int lastCol = region.getLastColumn(); Object mergedValue = headerRow0.get(firstCol); // 合并单元格的值在第1行的起始列 // 将值填充到第2行的合并列范围 for (int col = firstCol; col <= lastCol; col++) { headerRow1.set(col, mergedValue); } } } // 4. 确定目标列索引(A列→0,N列→13) int colDate = 0; // A列:数据日期 int colTotal = 13; // N列:总 // 5. 读取数据行(从第3行开始,索引2) int startRow = 2; int endRow = reader.getRowCount() - 1; // 最后一行索引 List<List<Object>> dataRows = reader.read(startRow, endRow); // 6. 遍历数据,提取目标列 for (List<Object> row : dataRows) { if (row.size() > colDate && row.size() > colTotal) { Object date = row.get(colDate); // 数据日期 Object total = row.get(colTotal); // 总 System.out.printf("数据日期:%s,总:%s%n", date, total); } } } finally { reader.close(); // 关闭资源 } } }
关键细节说明
下一篇: 面试官问我:你写代码会复用公共SQL么?