上传 xls,添加一些计算并在 Dash 中显示结果

Upload xls, add some calculations and show results in Dash

我正在尝试使用 Plotly Dash 对我的 Flask 应用程序执行一些操作。

基本上我想:

这是我的可重现代码。 我无法在加载 xls 文件后将结果显示为数据表。

谢谢

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)

这是因为您没有设置 DataTable 组件的 columns 属性。

您可以通过将 update_output 回调更改为如下内容来设置它:

@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

您可能已经这样做了,但是为了使 xlsx 工作,我必须安装 openpyxl。