Search code examples
pythonpython-3.xexceltkintertreeview

How to save a Treeview data as excel file in Tkinter?


I have some data in my Treeview Form which is binded to my SQLite database, I wonder if there is a way to save my Treeview's data as an excel file in my computer.

mytree = ttk.Treeview(frame_busqueda, height=19, column=('column1', 'column2', 'column3', 'column4', 'column5', 'column6'), show='headings', style="Custom.Treeview")
            mytree.pack()
style = ttk.Style()

style.configure("Custom.Treeview.Heading",
                             foreground="green", relief="flat", font='arial 10 bold')
style.map("Custom.Treeview.Heading", relief=[('active', 'groove'), ('pressed', 'sunken')])


mytree.heading("#1", text="ID CARD")
mytree.column("#1", minwidth=0, width=103, stretch=NO)
mytree.heading("#2", text="NAME")
mytree.column("#2", minwidth=0, width=200, stretch=NO)
mytree.heading("#3", text="SURNAME") 

def savetreeview():
     with open("new.csv", "w", newline='') as myfile:
          csvwriter = csv.writer(myfile, delimiter=',')

          for row_id in mytree.get_children():
              row = mytree.item(row_id)['values']
              csvwriter.writerow(row)
              print(row)

I was trying to use csv to try to get the rows, and it shows me all my Treeview data as output, but actually what I want is to save my Treeview's data as an excel file in my computer. Thanks


Solution

  • This is pretty simple with pandas, all you have to do is create a writer and use it to write the csv to excel, like:

    import pandas as pd
    
    writer = pd.ExcelWriter('nameofexcelfiletocreate.xlsx') # Creates this excel file
    df = pd.read_csv('new.csv') # Reads the csv and makes a dataframe
    
    df.to_excel(writer,'sheet1') # Writes the dataframe to excel file
    writer.save() # Saves the file
    

    This will create a new excel file with your csv converted to excel. Keep a note you have to install openpyxl for this to function:

    pip install openpyxl
    

    So your function would be something like:

    def call():
        cols = ['ID CARD','NAME','SURNAME'] # Your column headings here
        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()