Home > Software engineering >  Using tkinter asksaveasfilename, how to save dictionary of dataframes into seperate sheets in a new
Using tkinter asksaveasfilename, how to save dictionary of dataframes into seperate sheets in a new

Time:06-02

Right now I'm using the following command to save a dictionary of dataframes into seperate sheets in a new excel file:

# create dummy dataframe
data = [['A', 1], ['B', 2]]
df = pd.DataFrame(data, columns=['ColA', 'ColB'])
dict_df = {'df1': df, 'df2': df}

# save dict of df into excel
writer = ExcelWriter('filetosave.xlsx')
for key in dict_df:
    dict_df[key].to_excel(writer, key, index=False)
writer.save()

The code works fine but I'm trying to incorporate tkinter into my code so when my script runs, the file explorer will open up for me to name and save the file. However, the following code gives me an error.

from tkinter.filedialog import asksaveasfilename 
file = asksaveasfilename(defaultextension=".xlsx")
dict_df.to_excel(file)

AttributeError: 'dict' object has no attribute 'to_excel'

CodePudding user response:

You need to create the writer instance and go through the items inside dict_df like in the first code block:

from tkinter.filedialog import asksaveasfilename
from pandas import ExcelWriter

...

file = asksaveasfilename(defaultextension='.xlsx')
writer = ExcelWriter(file)
for key, df in dict_df.items():
    df.to_excel(writer, key, index=False)
writer.save()
  • Related