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

多Excel文件特定企业数据提取Python代码故障排查求助

问题排查与修复方案

原代码的核心问题

  1. 硬编码列名错误:代码里写死的Column_name肯定不是你Excel里实际存储企业信息的列名,这会直接导致KeyError
  2. 过时的合并方法:新版pandas已经移除了DataFrame.append()方法,用它会报错
  3. 格式支持不全:只处理.xlsx文件,漏掉了.xls格式的文件
  4. 匹配规则严格:默认区分大小写,若企业名称大小写不一致会漏数据
  5. 忽略多Sheet文件:只读取Excel的第一个Sheet,其他Sheet的数据会被漏掉

修正后的可运行代码

import os
import pandas as pd

def extract_company_data(folder_path, company_name, target_column):
    # 同时兼容xlsx和xls格式的Excel文件
    excel_files = [f for f in os.listdir(folder_path) 
                   if f.lower().endswith(('.xlsx', '.xls'))]

    # 用列表暂存每个文件筛选出的数据,提升合并效率
    extracted_list = []

    for file in excel_files:
        file_path = os.path.join(folder_path, file)
        try:
            # 读取Excel的所有Sheet,逐个处理
            xls = pd.ExcelFile(file_path)
            for sheet_name in xls.sheet_names:
                df = pd.read_excel(xls, sheet_name=sheet_name)
                # 先检查目标列是否存在,避免崩溃
                if target_column not in df.columns:
                    print(f"文件 {file} 的Sheet {sheet_name} 没找到列 {target_column},跳过")
                    continue
                # 不区分大小写匹配企业名称,自动忽略空值
                filtered_data = df[df[target_column].str.contains(company_name, na=False, case=False)]
                if not filtered_data.empty:
                    extracted_list.append(filtered_data)
                    print(f"文件 {file} 的Sheet {sheet_name} 提取到 {len(filtered_data)} 条数据")

        except Exception as e:
            print(f"处理文件 {file} 出错: {str(e)}")

    # 合并数据并保存
    if extracted_list:
        extracted_data = pd.concat(extracted_list, ignore_index=True)
        extracted_data.to_excel('extracted_data.xlsx', index=False)
        print(f"提取完成!共拿到 {len(extracted_data)} 条数据,已保存到 extracted_data.xlsx")
    else:
        print("没找到匹配指定企业的数据")

# --- 以下参数必须根据你的实际情况修改 ---
folder_path = r'C:\Users\mcaponigri\Downloads\CF-ABILITATI'  # 用原始字符串避免路径转义问题
company_name = 'BANCA MEDIOLANUM SPA'
# 替换成你Excel中存储企业信息的真实列名,比如'所属企业'、'Company'等
target_column = '企业名称'  

extract_company_data(folder_path, company_name, target_column)

使用前必做操作

  1. 修改列名参数:把target_column的值改成你Excel里实际存企业信息的列名,比如列叫公司名称就写'公司名称'
  2. 安装依赖库:如果没装pandas和相关Excel处理库,打开命令提示符运行:
pip install pandas openpyxl xlrd

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:17:33