2

I have a treeView witch has a lot of data I want to export this data to excel file. I want the simplest way to do this.

I have an idea witch is to convert whats in tree view to data frame then save the data frame as excel file. but I don't know if it's good idea or not ?!

from tkinter import filedialog
import pandas as pd
from collections import defaultdict

file = filedialog.asksaveasfilename(title="Select file","nameOfFile.xlsx",filetypes=[("Excel file", "*.xlsx")])
if file:
    ids=tree.get_children()
    dict = defaultdict(list)
    for id in ids:
        date=dt.datetime.strptime(tree.set(id, "#13"), '%Y-%m-%d %H:%M:%S')
        dateChosed=dt.datetime.strptime(monthToExport.get(), "%B-%Y")
        if (date.year == dateChosed.year) and (date.month == dateChosed.month):
            dict["1"].append(tree.item(id)["text"])
            dict["2"].append(tree.item(id)["values"][0])

    dict = pd.DataFrame.from_dict(dict)
    try:
        dict.to_excel(file, engine='xlsxwriter',index= False)
    except:
        print("Close the file than retry")
else:
    print("You did not save the file")
Ali
  • 687
  • 8
  • 27

2 Answers2

1
from tkinter import filedialog
import pandas as pd
from collections import defaultdict

file = filedialog.asksaveasfilename(title="Select file","nameOfFile.xlsx",filetypes[("Excel file", "*.xlsx")])
if file:
    ids=tree.get_children()
    dict = defaultdict(list)
    for id in ids:
        date=dt.datetime.strptime(tree.set(id, "#13"), '%Y-%m-%d %H:%M:%S')
        dateChosed=dt.datetime.strptime(monthToExport.get(), "%B-%Y")
        if (date.year == dateChosed.year) and (date.month == dateChosed.month):
            dict["1"].append(tree.item(id)["text"])
            dict["2"].append(tree.item(id)["values"][0])

    dict = pd.DataFrame.from_dict(dict)
    try:
       dict.to_excel(file, engine='xlsxwriter',index= False)
    except:
       print("Close the file than retry")
else:
print("You did not save the file")
Ali
  • 687
  • 8
  • 27
0
def save_csv():
    import csv
    with open("new.csv", "w", newline='') as myfile:
        csvwriter = csv.writer(myfile, delimiter=',')
        
        for row_id in st_trv.get_children():
            row = st_trv.item(row_id)['values']
            #print('save row:', row)
            csvwriter.writerow(row)
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57