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

如何将Excel命名区域导入Python并提取列转为列表?

解决方案:用Excel命名区域提取列数据为列表

你已经迈出了关键一步——用openpyxl识别出了命名区域的单元格范围,接下来我们可以通过两种方式实现“按命名区域提取列成列表”的需求,完全不需要依赖固定的列字母:

方案一:纯OpenPyXL处理(无需Pandas)

这个方法直接用openpyxl读取命名区域的单元格数据,然后按列整理成列表,适合不想引入额外库的场景:

from openpyxl import load_workbook

file = 'foo.xlsx'
wb = load_workbook(file, data_only=True)
target_name = 'mytest'

# 获取命名区域对应的工作表和单元格范围
# 假设命名区域只关联一个工作表(如果多个可循环处理)
sheetname, cell_address = list(wb.defined_names[target_name].destinations)[0]
cell_address = cell_address.replace('$', '')  # 去除绝对引用的$符号

# 获取目标工作表和指定区域的单元格
ws = wb[sheetname]
cell_range = ws[cell_address]

# 把行数据转置为列数据,再提取每列的数值
# 先把区域内的行转为列表
rows = list(cell_range)
# 转置得到列的迭代器,再逐个转为列表
column_data = []
for col in zip(*rows):
    # 处理空单元格:如果单元格无值则用None替代,可根据需求调整
    col_values = [cell.value if cell.value is not None else None for cell in col]
    column_data.append(col_values)

# 如果你的命名区域包含表头(比如第一行是列名),可以把表头和数据对应成字典
if len(rows) > 0:
    headers = [cell.value for cell in rows[0]]
    # 跳过表头行,取后面的数据列
    column_dict = dict(zip(headers, column_data[1:]))
    # 比如获取Height列的列表
    print(column_dict.get('Height', []))
else:
    print("命名区域为空")

方案二:结合Pandas处理(适合后续数据分析)

如果需要后续用Pandas做数据分析,可以先把命名区域的数据加载到DataFrame,再提取列列表:

from openpyxl import load_workbook
import pandas as pd

file = 'foo.xlsx'
target_name = 'mytest'

# 第一步:获取命名区域的详细信息
wb = load_workbook(file, data_only=True)
sheetname, cell_address = list(wb.defined_names[target_name].destinations)[0]
cell_address = cell_address.replace('$', '')

# 解析单元格范围,提取起始/结束的行和列
start_part, end_part = cell_address.split(':')
# 提取列字母(去除行号)
start_col = start_part.rstrip('0123456789')
end_col = end_part.rstrip('0123456789')
# 提取行号(去除列字母)
start_row = int(start_part.lstrip('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
end_row = int(end_part.lstrip('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

# 辅助函数:列字母和数字互相转换(用于生成列范围)
def col_to_num(col_letter):
    num = 0
    for c in col_letter.upper():
        num = num * 26 + (ord(c) - ord('A') + 1)
    return num

def num_to_col(col_num):
    col_letter = ''
    while col_num > 0:
        col_num, remainder = divmod(col_num - 1, 26)
        col_letter = chr(ord('A') + remainder) + col_letter
    return col_letter

# 生成需要读取的列字母列表
start_col_num = col_to_num(start_col)
end_col_num = col_to_num(end_col)
target_cols = [num_to_col(n) for n in range(start_col_num, end_col_num + 1)]

# 用Pandas读取指定区域的数据
df = pd.read_excel(
    file,
    sheet_name=sheetname,
    usecols=target_cols,
    skiprows=start_row - 1,  # 跳过起始行之前的所有行
    nrows=end_row - start_row + 1  # 读取的行数
)

# 提取指定列的列表,比如Height
height_list = df['Height'].tolist()
print(height_list)

这两种方案都完全依赖你预定义的命名区域,不管表格布局怎么调整,只要命名区域的范围更新了,代码就能自动读取最新的列数据,完美解决布局变动的问题!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:47:54