I decided to wrap the code in a component for convenience. Now (version 0.0.10), you can simply use the Download
component. Hence the previous example now look like this,
import io
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
# 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 csv", id="btn"), Download(id="download")])
@app.callback(Output("download", "data"), [Input("btn", "n_clicks")])
def generate_csv(n_nlicks):
# Convert data to a string.
s = io.StringIO()
df.to_csv(s, index=False)
content = s.getvalue()
# The output must follow this form for the download to work.
return dict(filename="some_name.csv", content=content, type="text/csv")
if __name__ == '__main__':
app.run_server()