Check if Sheet Exists After File Upload

Hello everybody!
Is it possible to check if an Excel sheet exists after uploading the file using st.file_uploader?

def my_func():
      input_file = st.file_uploader(Upload file", type="xlsx", accept_multiple_files=False)
      if input_file:
         df1 = pd.read_excel(input_file, sheet_name="sheetName1"
         df2 = pd.read_excel(input_file, sheet_name="sheetName2"

sheetName1 might not exist in some instances.

How do I check for its existence?

Thank you so much!

pandas.ExcelFile has a sheet_names attribute.

Awesome, great pointer!

I just canโ€™t figure out now how to trigger the true here:

if input_file:

        file = pd.ExcelFile(input_file)

        if file.sheet_names == "sheetName1":        < this is not triggering it
            st.info("Found")

The docs are not explict and I cannot test right now, but I donโ€™t expect something called sheet_names to be a string.

Iโ€™ll keep testing, and if you can also find something would be appreciated.

Thanks!

Try printing file.sheet_names to see how it looks like. And maybe type(file.sheet_names) to be sure.

I was doing that!

Seems they are strings


.

I was able to solve this using a for loop.

For those interested:

file = pd.ExcelFile(input_file)

for sheet in file.sheet_names:
      if sheet == "sheetName1":
          ...
      if sheet == "sheetName2"
          ...

Thank you @Goyo for the great suggestion.

You may want to learn about the in operator for sequence types.

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