使用Dash upload组件显示包含上传文件的pandas数据帧,可以按照以下步骤进行:
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 io
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Upload(
id='upload-data',
children=html.Div([
'拖放或 ',
html.A('选择文件')
]),
style={
'width': '50%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
multiple=False
),
html.Div(id='output-data')
])
@app.callback(Output('output-data', 'children'),
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')])
def update_output(contents, filename):
if contents is not None:
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# 读取上传的CSV文件
df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# 读取上传的Excel文件
df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
return html.Div([
'发生错误:',
html.Pre(str(e))
])
# 显示数据帧
return html.Div([
html.H5(filename),
html.Table(
[html.Tr([html.Th(col) for col in df.columns])] +
[html.Tr([
html.Td(df.iloc[i][col]) for col in df.columns
]) for i in range(min(len(df), 5))]
)
])
if __name__ == '__main__':
app.run_server(debug=True)
这样,你就可以使用Dash upload组件显示包含上传的文件的pandas数据帧了。用户可以通过上传文件的方式,将文件内容读取为pandas数据帧,并在界面上显示出来。
领取专属 10元无门槛券
手把手带您无忧上云