You could refer to Allowing users to download CSV on click to integrate this in a callback.
Hope the following example helps
import dash
import flask
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
from flask import send_file
import io
import pandas as pd
d = {"col1": [1, 2], "col2": [3, 4]}
df = pd.DataFrame(data=d)
app = dash.Dash()
app.layout = html.Div([
html.A("Download as Excel", id = 'my-link'),
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': '1', 'value': '1'},
{'label': '2', 'value': '2'},
],value='1'
)])
@app.callback(
Output('my-link', 'href'),
[Input('my-dropdown', 'value')])
def update_link(value):
return '/dash/urlToDownload?value={}'.format(value)
@app.server.route('/dash/urlToDownload')
def download_excel():
value = flask.request.args.get('value')
df1 = df['col{}'.format(value)]
buf = io.BytesIO()
excel_writer = pd.ExcelWriter(buf, engine="xlsxwriter")
df1.to_excel(excel_writer, sheet_name="sheet1", index=False)
excel_writer.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename="test11311.xlsx",
as_attachment=True,
cache_timeout=0
)
if __name__ == "__main__":
app.run_server(debug=False)