python-合并多个excel表格至一个excel多个sheet中

'''
将多个excel表格合并至一个excel多个sheet
'''

 1 import os
 2 import pandas as pd
 3 
 4 dir ='./tstdir'
 5 # 获取目录下所有的表
 6 origin_file_list = os.listdir(dir)
 7 print(origin_file_list)
 8 
 9 with pd.ExcelWriter('tables.xls') as writer:
10     # 循环遍历列表
11     for i in origin_file_list:
12         # 拼接每个文件的路径
13         file_path = dir + '/' + i
14         # 把表名赋予给对应的sheet,去掉文件类型.xlsx
15         sheet_name = i[:-5]
16         df = pd.read_excel(file_path)
17         df.to_excel(writer,sheet_name,index=False)
18         # 变相解决表格中第一行第一列为空的缺陷
19         string = "".join(list(str(i) for i in df.index))
20         # 判断如果索引都为数字,则不保留索引
21         if string.isdigit():
22              df.to_excel(writer,sheet_name,index=False)
23         else:
24              df.to_excel(writer,sheet_name)

 

posted on 2022-03-22 16:31  Wuxuanlin  阅读(976)  评论(0编辑  收藏  举报