多excel合并成1个excel不同sheet(含sheet重命名)

我有一个文件夹,文件夹里有多个excel,命名格式基本一致,每个excel中都有一个sheet,名为Sheet1,现要重命名每个文件的sheet名,重命名为原文件名列表中第12位到最后1位,并合成到一个新exel中。

python 复制代码
import os
import pandas as pd

# 获取文件夹中所有excel文件的文件名
folder_path = r'D:\data'
file_names = [f for f in os.listdir(folder_path) if f.endswith('.xls') or f.endswith('.xlsx')]

# 创建一个空的字典来存储所有数据
all_data = {}

# 遍历每个excel文件
for file_name in file_names:
    # 读取excel文件中的所有工作表名
    file_path = os.path.join(folder_path, file_name)
    xl = pd.ExcelFile(file_path)
    sheet_names = xl.sheet_names

    # 选择正确的工作表名(这里假设选择第一个工作表)
    selected_sheet_name = sheet_names[0]

    # 读取数据
    excel_data = pd.read_excel(file_path, sheet_name=selected_sheet_name)

    # 获取新的sheet名
    new_sheet_name = file_name[11:-4]  # 文件名前面11位为相同格式,用第12位到扩展名前结束,作为新的sheet名。

    # 重命名sheet
    excel_data.columns = [new_sheet_name + '_' + str(col) for col in excel_data.columns]

    # 将数据存储到all_data中
    all_data[new_sheet_name] = excel_data

# 将数据写入新的excel文件,每个工作表对应一个sheet
output_file_path = r'D:\数据合并.xlsx'
with pd.ExcelWriter(output_file_path) as writer:
    for sheet_name, data in all_data.items():
        data.to_excel(writer, sheet_name=sheet_name, index=False, header=False)
        # header=False 不显示重命名sheet名列索引
相关推荐
开开心心就好10 分钟前
视频里的图片怎么提取?双击一下就导出
java·前端·人工智能·spring·智能手机·intellij-idea·excel
葡萄城技术团队2 小时前
从 AI 生成到在线预览:dsh-spreadjs-editor 补齐 DSH 的 Excel 任务闭环
excel
泡海椒2 小时前
JQuick-Excel 实战:用 STYLE 配置单元格与区域样式
开发语言·python·excel
优选资讯12 小时前
标签打印软件怎么对接 Excel 数据
前端·excel
泡海椒16 小时前
JQuick-Excel 实战:FORMAT 管理日期与数字的 Excel 显示
开发语言·python·excel
AIGS00117 小时前
从814张表到250个本体:本体建模在做什么
数据库·excel·erp·数据中台·智能问数·本体语义·企业大脑
泡海椒19 小时前
JQuick-Excel VALIDATION 实战:用作用范围约束 Excel 导入校验
开发语言·python·excel
jason.zeng@150220721 小时前
(八)现有架构上新增一个通用Excel导出工具
python·架构·langchain·excel·llama
泡海椒21 小时前
JQuick-Excel 实战:用 VALIDATION 建立可维护的 Excel 导入校验
开发语言·python·excel
梁萌1 天前
影刀解决填充Excel数据不正确的问题
excel·rpa·墨刀