Send stored dataframe to excel


I have a dataframe (df_total) which I store in the buffer and send it to csv-file.
The below code works fine.

But I want to send the dataframe to an xlsx file. How would I have to modify the code below?

Thanks for help!

if not n_clicks:
      raise PreventUpdate
    download_buffer = io.StringIO()
    df_total.to_csv(download_buffer, index=False)
    return dict(content=download_buffer.getvalue(), filename="some_filename.csv")

Hello @slyfox,

There are a couple of ways to do this, here is one example via dash through a download button:

Here is a way that I use to write multiple sheets to one excel file:

        resp = io.BytesIO()

        with pd.ExcelWriter(resp, engine='xlsxwriter') as writer:
            data.to_excel(writer, sheet_name='data', index=False)
            data_calc.to_excel(writer, sheet_name='data2', index=False)
            costs.to_excel(writer, sheet_name='costs', index=False)
            if revenue is not None:
                revenue.to_excel(writer, sheet_name='revenue', index=False)

        return dcc.send_bytes(resp.getvalue(), 'data.xlsx')
1 Like

Thank you a lot! Great solution!

1 Like