Hi I am hoping someone can help me if possible.
I have a large spreadsheet of data that I have created a 'dictionary of data frames' I am however struggling to now export this to one excel file with each data frame having its own sheet in the excel document. As this could be used by other people I would also like to make the file export flexible ( it will be a clickable exe file)
I have looked at the following posts for help but just cant seem to get my head round it:
My code is as follows:
# Sort the Dataframe
df.sort_values(by = 'Itinerary_Departure_Date')
#Seperate Bookings By Itinerary
df_dict = dict(iter(df.groupby('Itinerary_Departure_Date')))
filepath = filedialog.asksaveasfilename(defaultextension = 'xlsx')
def frames_to_excel(df_dict, path = 'filepath'):
#Write dictionary of dataframes to separate sheets, within 1 file.
writer = pd.ExcelWriter(path, engine='xlsxwriter')
for tab_name, df_dict in df_dict.items():
df_dict.to_excel(writer, sheet_name=tab_name)
writer.save()
Fixed it!
Went down a different rabbit hole!
#Seperate Bookings By Itinerary
dict_of_itin = {k: v for k, v in df.groupby('Itinerary_Departure_Date')}
#Chooseemptyexcelfromwhereeversaved
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
book = load_workbook(file_path.replace('\\','/'))
writer = pd.ExcelWriter(file_path, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
for df_name, df in dict_of_itin.items():
df.to_excel(writer, sheet_name=df_name)
writer.save()
It relies on the person using it saving an empty spreadsheet first wherever they want but then will write to it.
not as elegant but it works! :D
Chris