多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名列索引
相关推荐
ohoy20 小时前
EasyPoi 自定义数据处理
excel
ohoy1 天前
easypoi 自定义样式 学生-分数红绿颜色设置
excel
ranchor6661 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas
Neoest1 天前
【Java 填坑日记】Excel里的“1.00“存入数据库解密后,Integer说它不认识:一次 NumberFormatException 翻车实录
java·数据库·excel
lzq6031 天前
Python自动化办公:5分钟批量处理Excel数据
python·自动化·excel
oh,huoyuyan1 天前
【实战案例】使用火语言RPA『表格数据提取』组件,批量爬取蔬菜价格+Excel 整理
爬虫·excel·rpa
缺点内向1 天前
如何在Excel文档中获取分页信息
后端·c#·.net·excel
黑客思维者1 天前
Python自动化办公全攻略:Excel/Word/PDF/邮件批量处理
python·自动化·excel
caleb_5202 天前
Excel导出问题:accessExternalStylesheet
excel
YANshangqian2 天前
图片转Excel表格
excel