Last active
October 27, 2020 01:56
-
-
Save philippschw/5d6696bb67dd4eb1ceab8dd70917e65e to your computer and use it in GitHub Desktop.
Create file dynamically and let the user download it as csv or excel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dash | |
from dash.dependencies import Input, Output | |
import dash_core_components as dcc | |
import dash_html_components as html | |
import pandas as pd | |
import urllib | |
import io | |
import flask | |
df = pd.DataFrame({ | |
'a': [1, 2, 3, 4], | |
'b': [2, 1, 5, 6], | |
'c': ['x', 'x', 'y', 'y'] | |
}) | |
def generate_table(dataframe, max_rows=10): | |
return html.Table( | |
# Header | |
[html.Tr([html.Th(col) for col in dataframe.columns])] + | |
# Body | |
[html.Tr([ | |
html.Td(dataframe.iloc[i][col]) for col in dataframe.columns | |
]) for i in range(min(len(dataframe), max_rows))] | |
) | |
app = dash.Dash(__name__) | |
app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"}) | |
app.layout = html.Div([ | |
html.Label('Filter'), | |
dcc.Dropdown( | |
id='field-dropdown', | |
options=[ | |
{'label': i, 'value': i} for i in | |
(['all'] + list(df['c'].unique()))], | |
value='all' | |
), | |
html.Div(id='table'), | |
html.A(html.Button('Export to Excel'), | |
id='download_xlsx'), | |
html.A( | |
html.Button('Export to CSV'), | |
id='download-link', | |
download="rawdata.csv", | |
href="", | |
target="_blank" | |
) | |
]) | |
def filter_data(value): | |
if value == 'all': | |
return df | |
else: | |
return df[df['c'] == value] | |
@app.callback( | |
Output('table', 'children'), | |
[Input('field-dropdown', 'value')]) | |
def update_table(filter_value): | |
dff = filter_data(filter_value) | |
return generate_table(dff) | |
@app.callback( | |
Output('download-link', 'href'), | |
[Input('field-dropdown', 'value')]) | |
def update_download_link(filter_value): | |
dff = filter_data(filter_value) | |
csv_string = dff.to_csv(index=False, encoding='utf-8') | |
csv_string = "data:text/csv;charset=utf-8," + urllib.parse.quote(csv_string) | |
return csv_string | |
@app.callback( | |
Output('download_xlsx', 'href'), | |
[Input('field-dropdown', 'value')]) | |
def update_download_link(filter_value): | |
return f'/export/excel?option={filter_value}' | |
@app.server.route('/export/excel') | |
def export_excel_file(): | |
option = flask.request.args.get('option') | |
option_df = filter_data(option) | |
xlsx_io = io.BytesIO() | |
writer = pd.ExcelWriter(xlsx_io, engine='xlsxwriter') | |
option_df.to_excel(writer, sheet_name='scheme', index=False) | |
writer.save() | |
xlsx_io.seek(0) | |
return flask.send_file( | |
xlsx_io, | |
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', | |
attachment_filename=f'export_{option}.xlsx', | |
as_attachment=True, | |
cache_timeout=0 | |
) | |
if __name__ == '__main__': | |
app.run_server(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I have a similar code to this (below) to download the csv from Dash and it worked perfectly in Chrome. However, the download doesn't work on Edge / IE. Have you experienced similar issue? Thanks.
@app.callback(
Output('download-link', 'href'),
[Input('field-dropdown', 'value')])
def update_download_link(filter_value):
dff = filter_data(filter_value)
csv_string = dff.to_csv(index=False, encoding='utf-8')
csv_string = "data:text/csv;charset=utf-8," + urllib.parse.quote(csv_string)
return csv_string