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)