[英]Excel and Python: Merge + Append multiple workbooks with multiple worksheets
我不完全確定從哪里開始這個項目,盡管我所做的研究有限,但我還沒有找到正確的答案或使用方法。
我有兩個 excel 工作簿,帶有多個工作表(選項卡)。 我正在嘗試將它們合並/附加到具有以下邏輯的單個 excel 表中:
工作簿 A = 主工作表 工作簿 B = 輔助工作表 所有工作表中的 A 列都是“索引” - 日期時間格式
在評論我的邏輯之后,這是答案:
import pandas as pd
masterPath = 'data/TrainingData.xlsx'
tempPath = 'data/WatchList - 2020-07-22 16-50.xlsx'
masterBook = pd.ExcelWriter(masterPath, engine='openpyxl')
tempBook = pd.ExcelWriter(tempPath, engine='openpyxl')
masterSheetNames = pd.ExcelFile(masterPath).sheet_names
tempSheetNames = pd.ExcelFile(tempPath).sheet_names
for sheetName in tempSheetNames:
if sheetName in masterSheetNames:
df_m = pd.read_excel(masterBook,
index_col=None,
na_values=['NA'],
sheet_name=sheetName)
df_t = pd.read_excel(tempBook,
index_col=None,
na_values=['NA'],
sheet_name=sheetName)
df_t.reset_index(drop=True, inplace=True)
df_m.reset_index(drop=True, inplace=True)
df = pd.concat([df_m, df_t], axis = 0, ignore_index=True)
df.drop_duplicates(subset=('Date'), keep='first', inplace=True)
df.set_index('Date', inplace=True)
df_t.to_excel(masterBook, sheet_name = sheetName)
else:
print(sheetName + ' will be added to Main doc')
df_t = pd.read_excel(tempBook,
index_col=None,
na_values=['NA'],
sheet_name=sheetName)
df_t.drop_duplicates(subset=('Date'), keep='first', inplace=True)
df_t.set_index('Date', inplace=True)
df_t.to_excel(masterBook, sheet_name = sheetName)
masterBook.save()
masterBook.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.