【发布时间】:2021-09-11 19:47:09
【问题描述】:
我正在使用 Python 在 Dash 中开发仪表板,并且在其中一个核心组件中我正在尝试上传 csv 文件并以数据表格式显示(见下文)。效果很好(见图),我按照这个例子:https://dash.plotly.com/dash-core-components/upload
但是,我还想在代码后面使用该表作为 pandas DataFrame。由于我在运行仪表板代码后上传了 csv 文件,因此我找不到将 csv 内容作为 DataFrame 返回的方法。有什么方法可以做到这一点?我的代码如下。
提前谢谢你!
###############################################################################
# Upload files
# https://dash.plotly.com/dash-core-components/upload
###############################################################################
def parse_contents(contents, filename, date):
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))
except Exception as e:
print(e)
return html.Div([
'There was an error processing this file.'
])
trade_upload = pd.DataFrame(df)
return dbc.Table.from_dataframe(trade_upload)
@app.callback(Output('output-data-upload', 'children'),
[Input('upload-data', 'contents')],
[State('upload-data', 'filename'),
State('upload-data', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
if list_of_contents is not None:
children = [
parse_contents(c, n, d) for c, n, d in
zip(list_of_contents, list_of_names, list_of_dates)]
return children
if __name__ == '__main__':
app.run_server(port=8051, debug=False)
【问题讨论】:
标签: python file-upload plotly-dash dashboard