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

Python解析Excel单元格标识 提取行列适配Pandas read_excel参数

实现方案

方案1:正则解析 + Pandas read_excel 原生实现

这个方案不需要引入额外依赖,核心用正则拆分Excel单元格引用的字母列和数字行:

核心逻辑

Excel单元格引用的规则是「1个或多个字母(列名)+1个或多个数字(行号)」,用正则r'([A-Za-z]+)(\d+)'可以直接匹配提取两部分内容,再按需求拼接参数即可。

代码示例

import re
import pandas as pd

def parse_cell_input(cell_str):
    # 拆分单元格范围
    cell_parts = cell_str.split(':')
    cols = []
    rows = []
    for part in cell_parts:
        match = re.match(r'^([A-Za-z]+)(\d+)$', part.strip())
        if not match:
            raise ValueError(f"无效的单元格格式: {part}")
        col, row = match.groups()
        cols.append(col.upper())
        rows.append(int(row))
    # 校验所有行号一致(适配同横行范围示例,跨行可自行扩展)
    if len(set(rows)) != 1:
        raise ValueError("暂不支持跨行的单元格范围")
    # 返回适配pandas的参数
    return {
        "usecols": ",".join(sorted(set(cols))),
        # skiprows是跳过前N行,要读第6行需要跳过前5行,如果你需要直接返回行号可以去掉-1
        "skiprows": rows[0] - 1 
    }

# 测试用例
print(parse_cell_input("C6")) # 输出: {'usecols': 'C', 'skiprows': 5}
print(parse_cell_input("AA62")) # 输出: {'usecols': 'AA', 'skiprows': 61}
print(parse_cell_input("A5:C5")) # 输出: {'usecols': 'A,C', 'skiprows': 4}

# 调用pandas读取
param = parse_cell_input("A5:C5")
df = pd.read_excel("你的文件路径.xlsx", usecols=param["usecols"], skiprows=param["skiprows"], nrows=1)

方案2:用openpyxl直接按单元格读取(更灵活)

如果不想适配pandas的参数规则,直接用openpyxl操作Excel可以直接按单元格标识取值,逻辑更直观,适合复杂的引用场景:

代码示例

from openpyxl import load_workbook

def read_by_cell(cell_str, file_path, sheet_name=None):
    wb = load_workbook(file_path, read_only=True, data_only=True)
    ws = wb[sheet_name] if sheet_name else wb.active
    if ":" in cell_str:
        # 范围读取
        return [cell.value for row in ws[cell_str] for cell in row]
    else:
        # 单个单元格读取
        return ws[cell_str].value

# 测试
print(read_by_cell("C6", "你的文件路径.xlsx"))
print(read_by_cell("A5:C5", "你的文件路径.xlsx"))
注意事项
  • 如果你需要支持跨行的单元格范围(比如A3:C5),只需要在方案1的解析逻辑里提取行的最小值和最大值,搭配pandas的nrows参数即可实现对应范围的读取
  • Excel的行号列号都是1开头,pandas的行索引默认是0开头,配置参数时可以根据实际需求调整偏移量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 21:54:04