I am trying to upload a file that contains multiple sheets. Within those sheets, I would like to create a DataTable for each sheet dynamically as my final sheet may have more tabs than what’s currently on there. I have referenced the this link but am still receiving errors. Code and errors below. I am not sure why my dictionary is giving me problems, I suspect its because its adding the sheet name as a key.
import base64
import pandas as pd
from dash import Dash, Input, Output, State, callback, dash_table, dcc, html
import pandas as pd
from dash import Dash, Input, Output, State, callback, dash_table, dcc, html
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
[
dcc.Upload(
id="upload-data",
children=html.Div(["Drag and Drop or ", html.A("Select Files")]),
style={
"width": "100%",
"height": "60px",
"lineHeight": "60px",
"borderWidth": "1px",
"borderStyle": "dashed",
"borderRadius": "5px",
"textAlign": "center",
"margin": "10px",
},
# multiple=True,
),
html.Div(id="tables-container"),
]
)
def parse_contents(contents, filename):
sheet_names = [
"Sheet1",
"Sheet2",
"Sheet3"
]
content_type, content_string = contents.split(",")
decoded = base64.b64decode(content_string)
# print(decoded)
try:
if "xlsx" in filename:
# Assume that the user uploaded an excel file
df_tmp = pd.read_excel(io.BytesIO(decoded), sheet_name=sheet_names)
except Exception as e:
print(e)
return html.Div(["There was an error processing this file."])
return df_tmp
@app.callback(
Output("tables-container", "children"),
Input("upload-data", "contents"),
State("upload-data", "filename"),
)
def update_output(contents, filename):
if contents:
data_output = parse_contents(contents, filename)
print(data_output)
print(type(data_output))
return dash_table.DataTable(data=data_output)
if __name__ == "__main__":
app.run(debug=True)
Error
dash.exceptions.InvalidCallbackReturnValue: The callback for `<Output `tables-container.children`>`
returned a value having type `DataTable`
which is not JSON serializable.
The value in question is either the only value returned,
or is in the top level of the returned list,
and has string representation
`DataTable(data={'Sheet1': A B C
0 50 81 68
1 35 68 88
2 45 97 100
3 54 43 57
4 95 36 42, 'Sheet2': A B C
0 35 37 15
1 96 87 81
2 50 76 66
3 20 63 54
4 15 83 39, 'Sheet3': A B C
0 29 85 81
1 72 5 87
2 26 42 4
3 90 22 35
4 9 19 20})`
In general, Dash properties can only be
dash components, strings, dictionaries, numbers, None,
or lists of those.