Streamlit to select excel sheet name and pass the selection to dataframe reader

Hi .

Can you please help on my below code , i am trying to read excel file by uploading it from local and then i need to choose sheetname , based on my sheetname i need to parse the excel and do some other logic .I am struck at selecting sheetname .After i choose sheetname i m not able to pass it to df reader can someone help

if page =="excel":
    st.subheader("Dataset")
    data_file = st.file_uploader("Upload excel",type=['xlsx'])  
    if st.button("Process"):
        if data_file is not None:
            file_details = {"Filename":data_file.name,"FileType":data_file.type,"FileSize":data_file.size}
            st.write(file_details)
            wb = openpyxl.load_workbook(data_file)
            sidebar = st.sidebar
            sheet_selector = sidebar.selectbox("Select sheetname",wb.sheetnames)     
            st.markdown(f"# Currently Selected {sheet_selector}")
            df = pd.read_excel(data_file,sheet_selector)

Nesting widgets after a button is not a good idea because it immediately goes back to a False state (There is a demo of that behavior in this video tutorial: Streamlit Shorts: How to combine a button, checkbox and radio buttion - YouTube).

A demo with your code:
selectSheet

st.header("Sheet view")
data_file = st.sidebar.file_uploader("Upload Excel file",type=['xlsx'])  

if data_file:
    file_details = {
        "Filename":data_file.name,
        "FileType":data_file.type,
        "FileSize":data_file.size}

    wb = openpyxl.load_workbook(data_file)

    ## Show Excel file
    st.sidebar.subheader("File details:")
    st.sidebar.json(file_details,expanded=False)
    st.sidebar.markdown("----")

    ## Select sheet
    sheet_selector = st.sidebar.selectbox("Select sheet:",wb.sheetnames)     
    df = pd.read_excel(data_file,sheet_selector)
    st.markdown(f"### Currently Selected: `{sheet_selector}`")
    st.write(df)

    ## Do something after a button
    doLogic_btn = st.button("βž•")
    if doLogic_btn:
        df2 = df.sum().transpose()
        st.write(df2)

        # Do something more after the previous button
        # >> But this will fail because the button will go back to _False_ 
        # >> so nothing will be shown afterwards
        another_btn = st.checkbox("Another +")
        if another_btn:
            df3 = df2.sum()
            st.write(df3)
4 Likes

Thanks a lot for your reply . this helped :slight_smile:

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.