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

Python Pandas读取Excel时如何适配仅存在其一的Blue/Purple工作表?

解决方案

实现思路

先读取Excel文件的工作表名称列表,定位到唯一存在的目标工作表(Blue或Purple),再将定位到的工作表名传入sheet_name参数即可适配当前场景。

完整适配代码

import pandas as pd
import os

# 拼接文件路径
excel_path = os.path.join(r, 'random_file.xlsx')
# 仅加载Excel文件索引,不读取全量数据
with pd.ExcelFile(excel_path) as xls:
    # 获取所有工作表名
    all_sheets = xls.sheet_names
    # 匹配唯一存在的目标工作表
    target_sheet = [s for s in all_sheets if s in ('Blue', 'Purple')][0]
    # 读取目标工作表内容
    tempTable = pd.read_excel(xls, 
                              sheet_name=target_sheet, 
                              header=10, 
                              nrows=10)

可选容错优化

如果需要适配生产环境的异常情况,避免出现匹配不到工作表、或两个工作表同时存在的问题,可以增加校验逻辑:

import pandas as pd
import os

excel_path = os.path.join(r, 'random_file.xlsx')
with pd.ExcelFile(excel_path) as xls:
    all_sheets = xls.sheet_names
    matched_sheets = [s for s in all_sheets if s in ('Blue', 'Purple')]
    # 增加异常校验
    if len(matched_sheets) != 1:
        raise ValueError("Excel文件不符合规则,未找到唯一的Blue/Purple工作表")
    target_sheet = matched_sheets[0]
    tempTable = pd.read_excel(xls, 
                              sheet_name=target_sheet, 
                              header=10, 
                              nrows=10)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:42:03