Reputation: 1858
I'm trying to do some operations with my Flask app using Plotly Dash.
Basically i would like to :
This is my reproducible code. I 'can't show the results as Datatable after loading xls file.
Thanks
import io
import datetime
import base64
import pandas as pd
import dash_table as dt
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from flask import Flask
FA = "https://use.fontawesome.com/releases/v5.15.1/css/all.css"
server = Flask(__name__)
app = dash.Dash(
name=__name__,
server=server,
external_stylesheets=[dbc.themes.BOOTSTRAP, FA],
suppress_callback_exceptions=True
)
# file upload function
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume that the user uploaded a CSV file
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
elif 'xlsx' in filename:
# Assume that the user uploaded an excel file
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print(e)
return None
return df
# callback table creation
@app.callback(Output('table', 'data'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def update_output(contents, filename):
if contents is not None:
df = parse_contents(contents, filename)
# add some operations/calculations and show results
if df is not None:
return df.to_dict('records')
else:
return [{}]
else:
return [{}]
app.layout = html.Div([
html.H5("Upload Files"),
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
multiple=False),
html.Br(),
html.H5("Updated Table"),
html.Div(dt.DataTable(data=[], id='table'))
])
if __name__ == "__main__":
app.run_server(port=8888)
Upvotes: 1
Views: 2028
Reputation: 15722
It's because you're not setting the columns
property of the DataTable
component.
You could set it by changing your update_output
callback to something like this:
@app.callback(
[Output("table", "data"), Output("table", "columns")],
[Input("upload-data", "contents"), Input("upload-data", "filename")],
)
def update_output(contents, filename):
if contents is not None:
df = parse_contents(contents, filename)
# add some operations/calculations and show results
if df is not None:
return df.to_dict("records"), [{"name": i, "id": i} for i in df.columns]
else:
return [{}], []
else:
return [{}], []
https://dash.plotly.com/datatable
Also you might already have done this, but for making xlsx work I had to install openpyxl.
Upvotes: 1