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

如何用Python合并文件夹中XLSM文件并将文件名置于首列

给合并后的表格添加来源文件名(A列)

直接给你修改好的脚本,核心是在读取每个文件后,往数据最前面插一列存文件名:

import os
import pandas as pd

data_file_folder = r"C:\..."

df = []
for file in os.listdir(data_file_folder):
    if file.endswith('.xlsm'):
        print('Loading file {0}...'.format(file))
        # 读取指定工作表
        temp_df = pd.read_excel(os.path.join(data_file_folder, file), sheet_name='B...')
        # 插入A列,列名可自定义,值为当前文件名
        temp_df.insert(0, '来源文件名', file)
        df.append(temp_df)

df_master = pd.concat(df, axis=0)
df_master.to_excel('A... .xlsx', index=False)

关键改动说明:

  • 把原脚本直接append的操作拆成两步:先将读取到的数据存入临时变量temp_df
  • 用temp_df.insert(0, '来源文件名', file)在第0列(对应Excel的A列)插入新列,列名可以根据需求修改(比如改为"数据来源文件"),列值就是当前处理的xlsm文件名
  • 处理后的临时DataFrame再加入合并列表,最终生成的表格会自动带上每条数据对应的来源文件名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:29:55