2

I'm following this guide and documentation in uploading an excel file into a dashboard: https://dash.plot.ly/dash-core-components/upload

I was wondering how I would display the results of my upload in a pandas dataframe. My code is outlined below. Essentially my table is a state breakdown of certain percentages and I'm trying to upload that into my dashboard.

import base64
import datetime
import io

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table

import pandas as pd


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.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': '120px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        # Allow multiple files to be uploaded
        multiple=True
    ),
    html.Div(id='output-data-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.'
        ])

def generate_table(df, max_rows=10):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in df.columns])] +

        # Body
        [html.Tr([
            html.Td(df.iloc[i][col]) for col in df.columns
        ]) for i in range(min(len(df), max_rows))]
    )

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children =[
    html.H4(children = 'test'),
    dcc.Dropdown( id = 'dropdown', options = [
        {'label' : i , 'value' : i} for i in df.state.unique()
    ],  multi = True, placeholder = 'Filter by State'),
    html.Div(id='table-container'),
        ])



def display_table(dropdown_value):

    if dropdown_value is None:
        return generate_table(df)


    #x = df[df['state'] == str(dropdown_value)]

    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),
        generate_table(df[df['state'].isin(dropdown_value)])

#app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})


@app.callback(
    dash.dependencies.Output('table-container', 'children'),
    [dash.dependencies.Input('dropdown','value')])


if __name__ == '__main__':
    app.run_server(debug=True)
ntwong
  • 89
  • 5
  • 1
    do you mean how do you display the pandas dataframe as it would look in output in a jupyter notebook? The question is a little unclear to me, as this tutorial already relies on reading data into pandas dataframes, and displaying them. – djakubosky Jun 21 '19 at 19:34
  • Hi @djakubosky, yes. I want to display the pandas dataframe as it would look in output in a Jupyter Notebook. Essentially I want to be able to use my dashboard, select and upload an excel file, and display the uploaded excel file in a pandas dataframe as it would look like in a jupyter notebook – ntwong Jun 24 '19 at 17:23
  • So it needs to preserve the "styling" of how it would render in the notebook. It seems this is a tricky thing based on a bit of digging. Rendering "raw" HTML isn't natively supported- but you can extract the style. I will post a possible solution – djakubosky Jun 25 '19 at 04:25

2 Answers2

1

Hi @ntwong I would recommend using dash_tables to display a dataframe, its the closest you will get. here is some basic code to get it working:

import dash_table
import pandas as pd
import dash_html_components as html

# create your dataframe "df" from your data idk what method you are using

    html.Div([
       dash_table.DataTable(data=df.to_dict("rows"), columns = [{"id": x, "name": x} for x in df.columns])
    ])

Just put the code in the body of your script.

sam c
  • 149
  • 1
  • 2
  • 9
0

Rendering raw HTML is discouraged, and others here have described instead functions to convert your parsed html to dash-html-components to use with dash_table. You might be able to make the table "look" like the one in the native jupyter by giving it the correct styling information- or you can download the dash-dangerously-set-inner-html package, which could let you display it.

An issue is that pandas returns just a basic html when you do df.to_html(), not one carrying any style attributes like in this question- you can possibly solve by rendering the df then getting the html (see below). Then you parse the html, extract the styles into a style dict. Then perhaps you could pass those styles to the dash_table using style_table/style_cell attributes.

html = (df.style.render())

Check out this guide for more info about building tables,

djakubosky
  • 907
  • 8
  • 15