pandas读写excel系列之拆分利用sheet做新excel名

pandas读写excel系列之拆分利用sheet做新excel名

需求具体为:
一个文件夹下有N个excel,每个excel有M个sheet,需要把每个exel中的每个sheet中内容拿出来放到一个新的excel,该excel的名字为改sheet名。所以最后得到N*M个excel。(暂不考虑sheet名字有重合的情况)

import os
import pandas as pd
def chaifen_excel(excel_path,new_excel_path):
    #底下的路径是要改的excel
    old_excel_path=excel_path
    #读取excel,提取所有sheet名字,后边作为新的excel名字
    data=pd.read_excel(old_excel_path,sheet_name=None)
    # print(data)
    #print(data.keys())
    new_excel_path=new_excel_path
    for sheetName in data.keys():
        sheet_data = pd.read_excel(old_excel_path,sheet_name=sheetName)
        #新建空的excel,名字为要写入的sheet名字,路径为原来的路径
        kong_excel=pd.DataFrame()
        kong_excel.to_excel(new_excel_path+sheetName+'.xlsx')
        #打开新建的空excel
        writer =pd.ExcelWriter(new_excel_path+sheetName+'.xlsx')
        # 写入,后边俩参数是写入时不要索引和列名
        sheet_data.to_excel(writer,index=False,header=False)
        writer.save()

#读取要拆分文件夹的文件目录
root_path="chaifen"
new_excel_path=root_path+'/'
file_list=os.listdir(root_path)
# print(file_list)
for i,excel in enumerate(file_list):
    old_excel_path=root_path+'/'+excel
    # print(old_excel_path)
    chaifen_excel(old_excel_path,new_excel_path)
    print("第"+str(i+1)+"个excel拆分完毕!")
# chaifen_excel(root_path)


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值