![](/img/trans.png)
[英]Python, how to combine different excel workbooks into one excel workbook as sheets
[英]Combine Multiple Excel sheets within Workbook into one sheet Python
所以我有 1500 個 Excel 工作簿,每個都有 10 多張結構完全相同的工作表。 我嘗試將多個 Excel 工作簿合並到一個文件中,並使用以下代碼成功:
import os
import pandas as pd
cwd = os.path.abspath('')
files = os.listdir(cwd)
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df = df.append(pd.read_excel(file), ignore_index=True)
df.head()
df.to_excel('Combined_Excels.xlsx')
結果,我得到了 Excel 工作簿的組合,但只有每個 Excel 工作簿的第一張(頁)。 我想我需要添加一個參數
sheet_name=None
,但是這樣我的 dataframe 就變成了一個dict
類型,當附加時,結果並不是我想要的。
import os
import pandas as pd
cwd = os.path.abspath('')
files = os.listdir(cwd)
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df = df.append(pd.read_excel(file, sheet_name=None), ignore_index=True)
df.head()
df.to_excel('Combined_Excels.xlsx')
各位有遇到過類似的問題嗎? 我怎樣才能至少將所有工作表合二為一? 將多個 Excel 表組合起來不會成為問題,因為第一個示例運行良好。
謝謝, 紐爾貝克
您可能會找到更好、更有效的方法來解決這個問題,但我就是這樣做的:
import os
import pandas as pd
# First, combine all the pages in each Workbook into one sheet
cwd = os.path.abspath('')
files = os.listdir(cwd)
df_toAppend = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df_toAppend = pd.concat(pd.read_excel(file, sheet_name=None), ignore_index=True)
df_toAppend.to_excel(file)
# And then append all the Workbooks into single Excel Workbook sheet
cwd_2 = os.path.abspath('')
files_2 = os.listdir(cwd_2)
df_toCombine = pd.DataFrame()
for file_2 in files_2:
if file_2.endswith('.xlsx'):
df_toCombine = df_toCombine.append(pd.read_excel(file_2), ignore_index=True)
df_toCombine.to_excel('Combined_Excels.xlsx')
對於大型數據集,合並可能需要相當長的時間。 希望這最終對某人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.