首页 > 解决方案 > 将多个 Excel 工作表合并为一个 Excel 工作表

问题描述

我有一个文件夹,我有 3 个 excel 文件,M、N、P 和 M、N、P 三张表 one_、two_ 和three_

Main
|
|_M.xlsx 
|       |_ one_M.xlsx
|       |_ two_M.xlsx
|       |_ three_M.xlsx
|       |_f_M.xlsx
|       |_O.M.xlsx
|_N.xlsx 
|       |_ one_N.xlsx
|       |_ two_N.xlsx
|       |_ three_N.xlsx
|       |_f_M.xlsx
|       |_O.M.xlsx
|_P.xlsx 
        |_ one_P.xlsx
        |_ two_P.xlsx
        |_ three_P.xlsx
        |_f_M.xlsx
        |_O.M.xlsx

我想要一个这样的合并后的excel文件

Main
|
|_Main.xlsx 
       |_ one_M.xlsx
       |_ two_M.xlsx
       |_ three_M.xlsx
       |_ one_N.xlsx
       |_ two_N.xlsx
       |_ three_N.xlsx
       |_ one_P.xlsx
       |_ two_P.xlsx
       |_ three_P.xlsx'

我怎样才能使用熊猫做到这一点

标签: pythonexcelpandas

解决方案


如果您使用sheet_name=Nonein pd.read_excel,您可以一次读取工作簿中的所有工作表。它们将与数据框合并到有序字典中。键将作为工作表的名称。

试试这个代码:

 df = pd.concat(pd.read_excel(workbook_path, sheet_name=None), ignore_index=True)

如果您只想将工作表合并到一个文件中:

 paths_list=['path1', 'path2',...]
 with pd.ExcelWriter('output_file_path.xlsx') as wr:
          For path in paths_list:
                 df=pd.read_excel(path, sheet_name =None)
                 [df[sheetName].to_excel(wr, sheet_name=sheetName) for sheetName in df] 

推荐阅读