Skip to content Skip to sidebar Skip to footer

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.Tree

Solution 1:

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

Solution 2:

def saveExcel():
    workbook = load_workbook(filename='problem record.xlsx')
    sheet=workbook['Sheet1']
    sheet.delete_rows(idx=2, amount=15)
    for row_id in treeview.get_children():
        row = treeview.item(row_id)['values']
        sheet.append(row)
    workbook.save(filename='problem record.xlsx')

Post a Comment for "How To Save A Treeview Data As Excel File In Tkinter?"