Read multiple excel tab with file uploader

I try to read multiple tab of an excel file with the file uploader in the streamlit. However, when running the following code with streamlit run, I will get the error:
ValueError: I/O operation on closed file.

Could anyone help me solve this problem?

I use Python 3.7 with streamlit in 0.60 version and pandas in 1.0.1 version.

import streamlit as st
import pandas as pd

file = st.file_uploader("Choose an excel file", type="xlsx")

if st.button('go!'):
        
    all_sheet = pd.ExcelFile(file)   
    sheets = all_sheet.sheet_names

    for i in range(len(sheets)):
        df = pd.read_excel(file, sheet_name = sheets[i])

You’re trying to repeatedly read the file, that’s the issue.

You can get individual sheets with all_sheet.parse(i) I think. Easier if you want all the sheets is to use pd.read_excel(file, None) and it’ll return a dictionary of sheet names and dataframes.

Also, really don’t recommend using a button here. If you have any other interaction on the page after it’ll be false when you change something. Better is just to check that the file isn’t falsy, then it’ll run on upload.

2 Likes