多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名列索引
相关推荐
SunnyDays10114 小时前
如何使用 Python 添加和编辑 Excel VBA 宏(无需安装 Excel)
开发语言·python·excel·vba
GHL2842710905 小时前
codex操作excel学习
学习·ai·word·excel
一晌小贪欢2 天前
python-第15天:Python 列表推导式
开发语言·python·excel·数据可视化·python办公
tryxr2 天前
Chat2Excel 项目通用服务开发
java·开发语言·excel·java项目开发
Jazz_z2 天前
使用 Python 合并与取消合并 Excel 单元格
开发语言·python·excel
2601_962381864 天前
Python办公联动:Excel数据一键自动生成PPT图表
python·数据分析·自动化·excel·ppt
tryCbest5 天前
Excel常用公式(WPS vs Office)
excel·wps
taller_20005 天前
【006】何时用 Python?何时用 Excel 公式?一文讲清
python·excel·公式·pie·py
2601_949950635 天前
Word、PDF、Excel题目怎么快速整理?
pdf·word·excel
Eiceblue6 天前
React 项目实战:用 JavaScript 合并多个本地 Excel 文件
前端·javascript·react.js·excel