多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名列索引
相关推荐
默默提升实验室3 小时前
Excel 数据透视表一键批量合并居中单元格(失效处理办法)
excel
Tony66668888811 小时前
EasyExcel导出多张图片
excel
罗政14 小时前
WPS Excel如何快速交换列(调整列顺序),删除多个不连续的列
excel·wps
小矮强14 小时前
Excel:通过身份证提取出生日期并计算年龄
excel
C#程序员一枚2 天前
导出百万量数据到Excel表
c#·excel
热心市民lcj2 天前
excel比较两列内容差异怎么弄,excel两个列进行数据比较。找A列有B列没有的数据显示到C列
excel
CodeCraft Studio2 天前
Excel处理控件Aspose.Cells教程:使用Python从Excel工作表中删除数据透视表
开发语言·python·excel·aspose·aspose.cells·数据透视表
开开心心_Every2 天前
Excel图片提取工具,批量导出无限制
学习·pdf·华为云·.net·excel·harmonyos·1024程序员节
一晌小贪欢2 天前
Pandas操作Excel使用手册大全:从基础到精通
开发语言·python·自动化·excel·pandas·办公自动化·python办公
清晨细雨~2 天前
SpringBoot整合EasyExcel实现Excel表头校验
spring boot·后端·excel