You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Apache POI与Java中使用配置列范围读取指定Excel列

解析配置列并提取Excel指定列的实现方案

核心思路

先把配置里的列表达式(比如B:F,I:K,L,P)拆成完整的列名列表,再转成Excel的列索引,最后读取Excel时只保留这些索引对应的列。


步骤1:编写列表达式解析工具

实现工具类,把配置的区间式列(如B:F)展开成单个列名,同时兼容单个列(如L、P):

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExcelColumnUtils {
    // 解析配置字符串,返回完整的目标列名列表
    public static List<String> parseColumnExpression(String columnExpr) {
        List<String> columns = new ArrayList<>();
        String[] parts = columnExpr.trim().split(",");
        // 匹配区间格式(如B:F)
        Pattern rangePattern = Pattern.compile("([A-Z]+):([A-Z]+)");
        
        for (String part : parts) {
            part = part.trim();
            Matcher matcher = rangePattern.matcher(part);
            if (matcher.matches()) {
                // 处理列区间:把B:F转换成B、C、D、E、F
                String startCol = matcher.group(1);
                String endCol = matcher.group(2);
                int startIndex = columnNameToIndex(startCol);
                int endIndex = columnNameToIndex(endCol);
                
                for (int i = startIndex; i <= endIndex; i++) {
                    columns.add(indexToColumnName(i));
                }
            } else {
                // 处理单个列,直接加入列表
                columns.add(part);
            }
        }
        return columns;
    }

    // 列名转索引(A=0,B=1,以此类推)
    public static int columnNameToIndex(String columnName) {
        int index = 0;
        for (char c : columnName.toUpperCase().toCharArray()) {
            index = index * 26 + (c - 'A' + 1);
        }
        return index - 1;
    }

    // 索引转列名(0=A,1=B,以此类推)
    public static String indexToColumnName(int index) {
        StringBuilder sb = new StringBuilder();
        index++; // 转换为1-based计算
        while (index > 0) {
            int remainder = index % 26;
            if (remainder == 0) {
                remainder = 26;
                index--;
            }
            sb.insert(0, (char)('A' + remainder - 1));
            index = index / 26;
        }
        return sb.toString();
    }
}

步骤2:读取Excel并过滤列

以Apache POI为例,实现读取逻辑,只保留目标列:

import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.util.List;
import java.util.stream.Collectors;

public class ExcelExtractor {
    // 从配置文件注入的列表达式,Spring环境可用@Value("${excel.specific.columns}")
    private String specificColumns;

    public void extractTargetColumns(String excelFilePath) throws Exception {
        // 1. 解析配置得到目标列的索引列表
        List<String> targetColumnNames = ExcelColumnUtils.parseColumnExpression(specificColumns);
        List<Integer> targetColumnIndexes = targetColumnNames.stream()
                .map(ExcelColumnUtils::columnNameToIndex)
                .collect(Collectors.toList());

        // 2. 读取Excel文件
        try (FileInputStream fis = new FileInputStream(excelFilePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            Sheet targetSheet = workbook.getSheetAt(0); // 读取第一个工作表,可根据需求调整
            for (Row row : targetSheet) {
                StringBuilder rowContent = new StringBuilder();
                // 只遍历目标索引的列
                for (int colIndex : targetColumnIndexes) {
                    Cell cell = row.getCell(colIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    // 根据单元格类型获取值
                    String cellValue = switch (cell.getCellType()) {
                        case STRING -> cell.getStringCellValue();
                        case NUMERIC -> String.valueOf(cell.getNumericCellValue());
                        case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
                        default -> "";
                    };
                    rowContent.append(cellValue).append("\t");
                }
                // 这里可以替换为写入新Excel、存入数据库等逻辑
                System.out.println(rowContent);
            }
        }
    }

    // 用于注入配置属性的setter(Spring环境可省略,直接用@Value)
    public void setSpecificColumns(String specificColumns) {
        this.specificColumns = specificColumns;
    }
}

依赖说明

如果用Maven,需要引入POI的依赖:

<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>

内容的提问来源于stack exchange,提问作者Sujit Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:50:22