Excel Writer to dcc.Download

Hi Eduardo – I think the below code covers the functionality that I needed it to (it might be a bit of over-engineering, so if you have any suggestions on how to keep the functionality while cleaning up the process, I would love to hear it) :smiley:. I really appreciate your help on this!

import tempfile

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np

app = dash.Dash(__name__)

app.layout = html.Div(
    children = [
        html.Button(
            id = 'export-button',
            children = 'Export',
        ),
        dcc.Download(
            id = "download-data"
        ),
    ]
)

@app.callback(
    Output('download-data', 'data'),
    Input('export-button', 'n_clicks'),
    prevent_initial_call = True
)
def export_data(n_clicks):
    with tempfile.TemporaryDirectory() as tmpdir:
        filename = 'placeholder.xlsx'
        
        df1 = pd.DataFrame(np.random.randint(0, 100, size = (17, 3)), columns = ['A', 'B', 'C'])
        df2 = pd.DataFrame(np.random.randint(0, 100, size = (17, 3)), columns = ['A', 'B', 'C'])
        df3 = pd.DataFrame(np.random.randint(0, 100, size = (17, 3)), columns = ['A', 'B', 'C'])

        with pd.ExcelWriter(f'{tmpdir}/placeholder.xlsx') as writer:
            df1.to_excel(writer, sheet_name = 'df1')
            df2.to_excel(writer, sheet_name = 'df2')
            df3.to_excel(writer, sheet_name = 'df3')

            return dcc.send_file(f'{tmpdir}/placeholder.xlsx')

if __name__ == '__main__':
    app.run_server(debug=True, port=8036)
3 Likes