Python 将树状视图中的内容导出到excel文件的最短方法是什么
我有一个树视图,它有很多数据,我想将这些数据导出到excel文件。 我想要最简单的方法来做这件事 我有一个想法是将树状图中的内容转换为数据框,然后将数据框保存为excel文件。 但我不知道这是不是个好主意Python 将树状视图中的内容导出到excel文件的最短方法是什么,python,tkinter,treeview,Python,Tkinter,Treeview,我有一个树视图,它有很多数据,我想将这些数据导出到excel文件。 我想要最简单的方法来做这件事 我有一个想法是将树状图中的内容转换为数据框,然后将数据框保存为excel文件。 但我不知道这是不是个好主意 from tkinter import filedialog import pandas as pd from collections import defaultdict file = filedialog.asksaveasfilename(title="Select file","na
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")
到目前为止你试过什么?有很多方法可以实现您想要的,是的,转换为dataframe然后保存到excel是一种有效的方法。@HenryYik这是我尝试的工作方法,如果它清晰的话,可以改进它。您可以使用defaultdict正确地保存几行,但除此之外,它看起来对我来说很好。@HenryYik thax需要您的帮助。
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")