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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM