如何仅提取多Excel文件中Applicant-New工作表的数据?
问题解决:仅提取Excel中"Applicant-New"工作表的数据
问题原因
你的代码直接强制读取名为"Applicant-New"的工作表,但没有判断当前文件是否存在该工作表,也没有匹配你提到的「每个文件第二个工作表是Applicant-New或Applicant-Recurring」的前提条件,导致错误读取到非目标数据;另外代码未初始化consolidated_df,运行时会触发未定义变量错误。
解决方案
方案1:检查文件中是否存在目标工作表
先获取每个Excel文件的所有工作表名称,仅当"Applicant-New"存在时才读取数据:
import pandas as pd import os path = os.getcwd() files_xlsx = [f for f in os.listdir(path) if f.endswith('.xlsx')] # 初始化空的结果DataFrame consolidated_df = pd.DataFrame(columns=["Application No."]) for file in files_xlsx: # 打开Excel文件并获取所有工作表名称 xls = pd.ExcelFile(file) sheet_names = xls.sheet_names if "Applicant-New" in sheet_names: # 读取目标工作表 df = pd.read_excel(xls, sheet_name="Applicant-New") new_row = {"Application No.": df.iloc[0, 0]} # 用concat替代已弃用的append方法 consolidated_df = pd.concat([consolidated_df, pd.DataFrame([new_row])], ignore_index=True)
方案2:针对第二个工作表进行判断
根据你提到的「每个文件第二个工作表是两种之一」的前提,直接获取第二个工作表名称,判断是否为目标后读取:
import pandas as pd import os path = os.getcwd() files_xlsx = [f for f in os.listdir(path) if f.endswith('.xlsx')] consolidated_df = pd.DataFrame(columns=["Application No."]) for file in files_xlsx: xls = pd.ExcelFile(file) # 获取第二个工作表名称(索引从0开始,第二个对应索引1) second_sheet = xls.sheet_names[1] if second_sheet == "Applicant-New": df = pd.read_excel(xls, sheet_name=second_sheet) new_row = {"Application No.": df.iloc[0, 0]} consolidated_df = pd.concat([consolidated_df, pd.DataFrame([new_row])], ignore_index=True)
关键优化点
- 使用
pd.ExcelFile先获取工作表列表,比直接读取更高效,适合批量处理文件 - 替换了pandas 2.0+已弃用的
append方法,改用pd.concat保证兼容性 - 提前初始化
consolidated_df,避免未定义变量错误 - 用
f.endswith('.xlsx')替代f[-4:] == 'xlsx',判断Excel文件更严谨
内容的提问来源于stack exchange,提问作者Rachael Loh
相关产品推荐
相关产品推荐

