Dropdown according to the names of the columns.

I’m trying to do a dropdown from an uploaded file, I already have the code to import the file as csv and excel, but I don’t know how to extract the names of the columns to use them in the dropdown.

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)

colors = {
‘background’: ‘#111111’,
‘text’: ‘#7FDBFF
}

app.layout = html.Div([ #Visualizador en la web.
dcc.Upload(
id=‘upload-data’,

    children=html.Div([
        'Arrastrar y soltar'#,
        #html.A('Seleccionar archivos')
    ]),
    style={
        'width': '10%',
        'height': '50px',
        'lineHeight': '50px',
        'borderWidth': '1px',
        'borderStyle': 'dashed',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '30px',
        'background': colors['background'],
        'color': colors['text']
    },
    # Permitir que se carguen varios archivos
    multiple=True
),

html.Div(children=[ #div gigante, que contiene los siguientes children
    dcc.Dropdown(
            options=[{'label': i, 'value': i} for i in data],
            style={'background': colors['background'],
           'textAlign': 'center',
           'color': colors['text']},
            multi=True,
            value="MTL"

),
],
style={‘background’: colors[‘background’],
‘textAlign’: ‘center’,
‘color’: colors[‘text’]}),

html.Div(id='output-data-upload', style={
    'textAlign': 'center',
    'background': colors['background']
    #'color': '#111111'
}),

],
style={‘background’: colors[‘background’]}
)

def parse_contents(contents, filename, date):
content_type, content_string = contents.split(’,’)

decoded = base64.b64decode(content_string)
try:
    if 'csv' in filename:
        # Suponga que el usuario ha subido un archivo CSV
        df = pd.read_csv(
            io.StringIO(decoded.decode('utf-8')))
    elif 'xls' in filename:
        # Suponga que el usuario ha subido un archivo excel.
        df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
    print(e)
    return html.Div([
        'Se ha producido un error al procesar este archivo.'
    ])

return html.Div([
    html.H5(filename),
    html.H6(datetime.datetime.fromtimestamp(date)),

    dash_table.DataTable(
        data=df.to_dict('records'),
        columns=[{'name': i, 'id': i} for i in df.columns]
    ),
    df,

    html.Hr(),  # horizontal line

    # Para depurar, muestre el contenido en bruto proporcionado por el navegador web
    
    html.Div('Raw Content'),
    html.Pre(contents[0:5] + '...', style={
        'whiteSpace': 'pre-wrap',
        'wordBreak': 'break-all',
        'background': colors['background']
    })
])

@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(debug=True)```

1 Like