Dash Download In-memory Generated File On Button Click: How To Give Filename?
I generate an in-memory Excel file via pd.ExcelWriter and BytesIO for a click event in my Python3.8 dash app. Everything works as it should be. When I download my file I get this
Solution 1:
You could use the Download
component from the dash-extensions package,
pip install dash-extensions == 0.0.18
The syntax is simpler, and it has a filename
argument. Here is a small example,
import dash
import dash_html_components as html
import numpy as np
import pandas as pd
from dash.dependencies import Output, Input
from dash_extensions import Download
from dash_extensions.snippets import send_bytes
# Generate some example data.
data = np.column_stack((np.arange(10), np.arange(10) * 2))
df = pd.DataFrame(columns=["a column", "another column"], data=data)
# Create app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Download xlsx", id="btn"), Download(id="download")])
@app.callback(Output("download", "data"), [Input("btn", "n_clicks")])defgenerate_xlsx(n_nlicks):
defto_xlsx(bytes_io):
xslx_writer = pd.ExcelWriter(bytes_io, engine="xlsxwriter")
df.to_excel(xslx_writer, index=False, sheet_name="sheet1")
xslx_writer.save()
return send_bytes(to_xlsx, "some_name.xlsx")
if __name__ == '__main__':
app.run_server()
Disclaimer: I am the author of the dash-extensions package.
Post a Comment for "Dash Download In-memory Generated File On Button Click: How To Give Filename?"