什么是将树视图中的内容导出到excel文件的最短方法

时间:2019-05-23 08:32:23

标签: python tkinter treeview

我有一个treeView女巫,其中有很多数据,我想将此数据导出到excel文件。 我想要最简单的方法。

我有一个主意,就是将树状视图中的内容转换为数据框,然后将数据框另存为excel文件。 但我不知道这是个好主意吗?!

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

1 个答案:

答案 0 :(得分: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")
相关问题