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

使用Python解析.xlsx文件,如何关联行列提取符合指定条件的ID

实现方案

方案1:使用pandas实现(推荐,代码最简洁)

该方案适合绝大多数表格处理场景,无需手动处理行列索引,代码可读性和可维护性更高。
先安装依赖库:
pip install pandas openpyxl
实现代码:

import pandas as pd

# 读取指定sheet的xlsx文件
df = pd.read_excel('你的文件路径.xlsx', sheet_name='wanted_sheet')

# 筛选Column1为FREE的行,这里做了去空格、统一转大写处理,适配示例中Free/FREE大小写混用的情况
filtered_df = df[df['Column1'].str.strip().str.upper() == 'FREE']

# 提取对应的ID列表
target_ids = filtered_df['ID'].tolist()

# 打印结果验证
print(target_ids)

方案2:修正现有xlrd实现

适配你当前的xlrd技术栈,解决原有代码ID和状态未关联的问题。
注意:xlrd 2.0及以上版本不再支持.xlsx格式读取,如需使用该库请安装1.2.0版本:pip install xlrd==1.2.0
实现代码:

import xlrd

file_location = '你的文件路径.xlsx'
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_name('wanted_sheet')

target_ids = []
# 从第1行开始遍历,跳过表头行,若你的表格无表头则从第0行开始遍历即可
for row_idx in range(1, sheet.nrows):
    # 取当前行第0列的ID值
    current_id = sheet.cell_value(row_idx, 0)
    # 取当前行第1列的Column1值,做去空格、转大写处理适配大小写差异
    current_state = sheet.cell_value(row_idx, 1).strip().upper()
    if current_state == 'FREE':
        target_ids.append(current_id)

# 打印结果验证
print(target_ids)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:36:05