![](/img/trans.png)
[英]Python: How to copy Excel worksheet from multiple Excel files to one Excel file that contains all the worksheets from other Excel files
[英]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.