当前位置: 首页 > 知识库问答 >
问题:

将工作簿中的多个Excel工作表合并为一个工作表Python

赏夕
2023-03-14

所以我有 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')

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')

谢谢,努尔贝克

共有1个答案

苏磊
2023-03-14

您可能会找到更好、更有效的方法来解决这个问题,但我是这样做的:

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')

对于大数据集,可能需要相当多的时间来组合。希望这最终能帮助到某人。

 类似资料: