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

如何用代码批量提取300份多标签Excel指定单元格数据并合并?

批量处理不规范Excel并合并数据解决方案

所需依赖

  • 先安装必要的Python库:
    pip install pandas openpyxl
    
    若处理.xls格式文件,需替换引擎为xlrd并安装对应版本:
    pip install xlrd==1.2.0
    

代码实现

1. 单个Tab的处理逻辑

从指定单元格提取列名与对应值,返回单行DataFrame:

import pandas as pd
import os

def process_single_tab(worksheet):
    # 定义列名单元格和对应值单元格的映射关系
    cell_pairs = {
        'A3': 'B3',
        'C6': 'F6',
        'C7': 'F7',
        'C9': 'F9',
        'C10': 'F10',
        'C12': 'F12',
        'C14': 'F14',
        'C17': 'F17',
        'C19': 'F19'
    }
    
    row_data = {}
    for col_cell, val_cell in cell_pairs.items():
        row_data[worksheet[col_cell].value] = [worksheet[val_cell].value]
    
    return pd.DataFrame(row_data)

2. 单个Excel文件的处理逻辑

遍历文件内所有Tab,合并数据并添加Tab名称、文件名标识:

def process_single_excel(file_path):
    xls = pd.ExcelFile(file_path, engine='openpyxl')
    tab_dfs = []
    
    for tab_name in xls.sheet_names:
        # 获取原生worksheet对象以读取指定单元格
        worksheet = xls.book[tab_name]
        tab_df = process_single_tab(worksheet)
        tab_df['TabName'] = tab_name
        tab_df['FileName'] = os.path.basename(file_path)
        tab_dfs.append(tab_df)
    
    return pd.concat(tab_dfs, ignore_index=True)

3. 批量处理目录下所有Excel

遍历目标目录,处理所有文件并合并为最终数据集:

def batch_process_dir(dir_path):
    all_data = []
    for filename in os.listdir(dir_path):
        if filename.endswith(('.xlsx', '.xls')):
            file_path = os.path.join(dir_path, filename)
            print(f"处理中:{filename}")
            try:
                file_df = process_single_excel(file_path)
                all_data.append(file_df)
            except Exception as e:
                print(f"处理{filename}出错:{str(e)}")
                continue
    
    return pd.concat(all_data, ignore_index=True)

执行脚本

# 替换为你的Excel文件所在目录
target_directory = r'C:\你的Excel文件存放路径'
final_df = batch_process_dir(target_directory)

# 保存合并结果
final_df.to_excel('合并总数据.xlsx', index=False, engine='openpyxl')
print("处理完成,结果已保存为'合并总数据.xlsx'")

注意事项

  • 若存在个别文件格式异常,代码中的try-except会跳过错误文件并打印提示,方便排查
  • FileName列用于溯源原始文件,可根据需求删除
  • 确保所有Excel文件的指定单元格位置统一,避免提取数据偏差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:48:30