Uploading CSV and excel files

Hi,

Thanks for your great work!

My website allows the user to upload CSV files. I would like to add the possibility, using the same widget, to upload Excel files. It does not work I think for an issue of encoding that I was unable to solve.

At the moment I upload csv files like so:

    try:
          bytesData = uploadedFile.getvalue()
          encoding = encodingUTF8 
          s=str(bytesData,encoding)
          result = StringIO(s) 
    except:
          bytesData = uploadedFile.getvalue()
          encoding = encodingISO 
          s=str(bytesData,encoding)
          result = StringIO(s)  

This works fine. I wanted to add the possibility for the user also to upload xlsx files, so I changed the file uploaded code to

        uploadedFile = st.file_uploader(fileUploadLabel, type=['csv','xlsx'],accept_multiple_files=False,key="fileUploader")

and added a “read excel” bit

  try:
        df=pd.read_csv(dataUploaded, error_bad_lines=True, warn_bad_lines=False,sep=chosenFileSeparator)
  except:
        try:
              df = pd.read_excel(dataUploaded)
        except:      
              df=pd.DataFrame()

I get this error (if I take out the “try” or course)

The identical file just in CSV instead of Excel gets read with not problem.

Thanks so much for your help!

Fabio

1 Like

@Fabio Hi, you can just use st.file_uploader(“the notice you want to tell”) to finish upload function.
both csv and xls or xlsx file can be uploaded.
example:

import pandas as pd
import streamlit as st
uploaded_file = st.file_uploader(“Choose a file”)
if uploaded_file is not None:
#read csv
df1=pd.read_csv(uploaded_file)

   #read xls or xlsx
   df1=pd.read_excel(uploaded_file)

else:
st.warning(“you need to upload a csv or excel file.”)

if you want to capture the file name of uploaded, you can write code like this:
filename=uploaded_file.name

1 Like

Hi @BeyondMyself,

thanks for your answer!

In my case the problem is that I do not know beforehand whether the file will be CSV or xlsx.

Since (I suppose) csv and excel files have a different encoding, I suppose that something bad happens in my encoding function

   try:
      bytesData = uploadedFile.getvalue()
      encoding = encodingUTF8 
      s=str(bytesData,encoding)
      result = StringIO(s) 

I do not get an error here, but then when I run “read_excel” on the object returned from my “StringIO(s)” function, I get the error.

try:
          df = pd.read_excel(dataUploaded)
    except:      
          df=pd.DataFrame()

Are you saying that filename=uploaded_file.name will give me also the file suffix (csv or xlsx) :slight_smile: not just the file name ?

Thanks again!

Fabio

Yes it returns also the suffix!!! :slight_smile: