繁体   English   中英

如何使用 python 将 Excel 文件中的所有工作表合并或合并到一个工作表中?

[英]How can combine or merge all worksheets within an Excel file into one worksheet using python?

我正在尝试将提供的文件路径中每个 excel 文件的所有工作表选项卡合并到一个工作表中。 例如,如果有 5 个带有多个金额工作表选项卡的 Excel 文件,则每个 Excel 文件现在只包含一个合并的工作表选项卡。 我想将这些合并的工作表选项卡中的每一个附加到创建的输出文件中。

我下面的代码能够将提供的源文件中的所有工作表选项卡附加到输出文件,但我不知道如何首先合并源中的工作表选项卡。 有谁知道我该如何做到这一点? 请在下面查看我的代码 - 谢谢!:

import glob
import os
import pandas as pd
import sys
import os.path
from openpyxl import load_workbook
from openpyxl import Workbook

#System Arguments
folder = sys.argv[1]
inputFile = sys.argv[2]
outputFile = sys.argv[3]

# specifying the path to xlsx files
path = r""+folder+""

#Create the new Excel Workbook with nameing convention provided by user
def create_file():
    wb = Workbook()
    wb.save(outputFile)

#Append the NEW or EXISTING Workbook with Input Files and Tabs to the already existing Excel File
def appened_file():
    outputPath = outputFile
    book = load_workbook(outputPath)
    writer = pd.ExcelWriter(outputPath, engine = 'openpyxl', mode="a", if_sheet_exists="new")
    writer.book = book
    for filename in glob.glob(path + "*" + inputFile + "*"):
            print(filename)
            excel_file = pd.ExcelFile(filename)
            (_, f_name) = os.path.split(filename)
            (f_short_name, _) = os.path.splitext(f_name)
            for sheet_name in excel_file.sheet_names:
                df_excel = pd.read_excel(filename, sheet_name=sheet_name,engine='openpyxl')
                df_newSheets = pd.DataFrame(df_excel)
                df_newSheets.to_excel(writer, sheet_name, index=False)                   
    writer.save()




您可以仅使用 pandas 来执行此操作,因为pd.read_excel可以一次读取工作簿的所有工作表:

import pandas as pd

path = r"test.xlsx"
path_save = r"result.xlsx"

df_dict = pd.read_excel(path, sheet_name=None)
df_dict = {k: v.transpose().reset_index().transpose() for k, v in df_dict.items()}
df_result = pd.concat(df_dict.values(), ignore_index=True)
df_result.to_excel(path_save, index=False, header=False)

我认为使用 xlwings 或 openpyxl 也可以做到这一点,但通常 pandas 很快。

数据示例
假设一个 Excel 工作簿包含三个工作表。

工作表1:

a   b   c
foo cor wal
bar gra plu
baz ult xyz
qux ply thu

工作表2:

u   v   w   x   y   z
12  92  86  22      80
23  29      74      21
16  10  75  67  61  99

工作表3:

I   II  III IV
1   5   9   1
2   6   0   6
3   7       3
4   8   2   0

最终输出(在执行此代码段之后,即在to_excel之后):

a   b   c
foo cor wal
bar gra plu
baz ult xyz
qux ply thu
u   v   w   x   y   z
12  92  86  22      80
23  29      74      21
16  10  75  67  61  99
I   II  III IV
1   5   9   1
2   6   0   6
3   7       3
4   8   2   0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM