簡體   English   中英

使用 pandas 和 openxlpy 將 DF 寫入現有的 Excel 文件

[英]Write DF to existing Excel file with pandas and openxlpy

我正在嘗試將 df 寫入現有的工作表。 最初程序會打開一個對話框給 select 一個要添加的新工作表名稱,然后找到 excel 工作表的路徑。

#reload window to select new sheet name
root = tk.Tk()
root.geometry('500x200+350+150')
root.configure(bg='#072462')

#set buttons
label_date = Label(root, text='Input New Sheet Name', bg='#072462', fg='white')
ws_new_title = Entry(root, width=45, bg='#0A1944', fg='white', highlightthickness=0, borderwidth=0)
ws_new_title.insert(0, 'YYYY-MM-DD') #insert guide text in box
button_ws_name = Button(root, width=20, text='Select Export Excel File', command=root.quit)
button_ws_name.configure(fg='#C51E42', bg='#06122f', borderwidth=5)

label_date.pack()
ws_new_title.pack()
button_ws_name.pack(pady=30)
root.mainloop()

用於查找 excel 路徑的對話框代碼(工作)

#find and save to new excel sheet based on a input of name
root = tk.Tk()
root.title('Great Britain Basketball')
root.withdraw()
file_path_export = filedialog.askopenfilename(initialdir='/Desktop/', title='Select Player Tracking document')
root.update()
export_fn = file_path_export

打開工作簿並添加新工作表的代碼(認為這個。可能是錯誤的)

book = load_workbook(export_fn)
writer = pd.ExcelWriter(export_fn, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

最后將 df (full_append) 寫入 excel

full_append.to_excel(writer, startrow=len(df)+1, index=False, header=False, sheet_name='Season Data') #working -write to exsisting sheet and append to bottom row
full_append.to_excel(writer, sheet_name=ws_new_title, index=False) #not working - write to same sheet but on seperate sheet taking name from input
writer.save()

所以主要問題是程序沒有使用規定的工作表名稱(ws_new_title 變量)在工作簿中添加新工作表,並將 df 寫入其中。 謝謝

設法找到語法錯誤。 設置進入按鈕后

ws_new_title = Entry(root, width=45, bg='#0A1944', fg='white', highlightthickness=0, borderwidth=0)

在將其用作現有 Excel 工作表中的新工作表名稱之前,我需要將此條目更改為字符串變量。 為此,我使用了 a.get() function

#change entry to a string
ws_name = ws_new_title.get()

然后最后 append df 到“季節數據”並根據日期保存到新工作表

#write to excel workbook
book = load_workbook(export_fn)
writer = pd.ExcelWriter(export_fn, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

full_data_table.to_excel(writer, sheet_name=ws_name, index=False) #working but need to update name based on input
full_data_table.to_excel(writer, startrow=len(df)+1, index=False, header=False, sheet_name='Season Data') #working -write to exsisting sheet and append to bottom row

writer.save()
writer.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM