簡體   English   中英

如何將我的所有 Treeview 數據以及特定數據保存在不同的 Excel 文件中?

[英]How to save all my Treeview's data and also specific data in different Excel files?

我正在嘗試將樹視圖的數據保存在不同的 Excel 文件中,實際上我的代碼正在工作,每次我想保存它時都在同一個 Excel 文件中更新我的數據,所以我想要保存在不同的文件中。 我的意思是,當我按下保存按鈕時,它會顯示“我想將其保存在計算機中的哪個位置”以及“給該文件起什么名稱”,然后只顯示一條消息“已成功保存”或“您沒有 select 任何數據”為了節省”。 這是我將數據保存在同一文件中的代碼:

def save():
    cols = ['ID CARD','NAME','SURNAME', 'DATE']
    path = 'read.csv'
    excel_name = 'newfile.xlsx'
    lst = []
    with open(path, "w", newline='') as myfile:
        csvwriter = csv.writer(myfile, delimiter=',')
        for row_id in mytree.get_children():
            row = mytree.item(row_id,'values')
            lst.append(row)
        lst = list(map(list,lst))
        lst.insert(0,cols)
        for row in lst:
            csvwriter.writerow(row)

    writer = pd.ExcelWriter(excel_name)
    df = pd.read_csv(path)
    df.to_excel(writer,'sheetname')
    writer.save() 

這樣做並不難,您必須使用filedialog中的tkinter

from tkinter import filedialog, messagebox

然后將excel_name替換為:

excel_name = filedialog.asksaveasfilename(title='Save location',defaultextension=[('Excel','*.xlsx')],filetypes=[('Excel','*.xlsx')]) 

這應該會彈出一個文件對話框,詢問您保存文件的位置,然后邏輯將文件保存在返回的位置。 您可以使用messagebox使其變得更好,例如:

excel_name = filedialog.asksaveasfilename(title='Save location',defaultextension=[('Excel','*.xlsx')],filetypes=[('Excel','*.xlsx')]) 

if not excel_name or excel_name == '/': # If the user closes the dialog without choosing location
    messagebox.showerror('Error','Choose a location to save')
    return # Stop the function 

雖然我不確定每次用戶關閉時excel_name是否會是'''/' ,但請使用print(excel_name)並關閉該框,然后使用打印出的任何內容進行if

更多關於帶有 tkinter 的文件對話框: Tkinter 對話框 — Python 3.9.2 文檔

暫無
暫無

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

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