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

2024-09-30 02:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个树视图,它有很多数据,我想把这些数据导出到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")

Tags: 文件数据fromimportidtreedatexlsx
1条回答
网友
1楼 · 发布于 2024-09-30 02:19:55
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")

相关问题 更多 >

    热门问题