Search code examples
pythonpython-3.xexceltkintertreeview

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


I'm trying to save my treeview's data in different Excel files, actually my code is working UPDATING my data in the same Excel file every time I want to save it, so What I want is to save in different files. I mean when I push my save button it shows 'where I want to save it in my computer' also 'what name to give that file', then just show a message 'saved successfully' or just 'You didn't select any data for saving'. This is my code which is saving the data in the same file:

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() 

Solution

  • It wouldnt be so hard to do this, you have to use filedialog from tkinter:

    from tkinter import filedialog, messagebox
    

    and then replace excel_name with:

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

    This should bring up a file dialog asking you a location to save the file, after which the logic saves the file on the returned location. You can make this more better with messagebox, like:

    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 
    

    Though I am not sure on if excel_name will be '' or '/' everytime the user closes, use print(excel_name) and close the box and then make the if with whatever is printed out.

    More about filedialog with tkinter: Tkinter Dialogs — Python 3.9.2 documentation