How to get columns of uploaded excel file?

On Discord (link) jase64 asks how to get the columns of an uploaded excel file.

You are almost there. The error you mention

Is because you are taking columns on the function fn_uploaded. Instead you should run the function fn_uploaded() as this will return the dataframe. Then you can take get the columns fn_uploaded().columns.


In Panel you would often pn.bind, @pn.depends or use pn.rx on the function fn_uploaded. For example like below.

import pandas as pd
import panel as pn
import io

pn.extension("tabulator")

file_input = pn.widgets.FileInput()

def get_data(file):
    if file is not None:
        df = pd.read_excel(io.BytesIO(file), engine='openpyxl')
        return df
    return pd.DataFrame()

upload = pn.widgets.FileInput(accept='.xlsx', multiple=False)

fn_uploaded = pn.bind(get_data, file=upload.param.value)

def get_columns(df):
    return f"Columns: {df.columns.tolist()}"
columns = pn.bind(get_columns, df=fn_uploaded)

pn.Column(
    upload,
    pn.pane.Str(fn_uploaded, height=75),
    columns,
).servable()