Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Data Connections

Files, CSV and Excel in Streamlit

Let users upload CSV, Excel and JSON files in Streamlit, read them with pandas, validate columns, handle large files and offer results through download buttons.

Most data apps start with a file. A user drops a spreadsheet on the page, you read it into a pandas DataFrame, show a table and a chart, and let them download the cleaned result. Streamlit has a widget for each end of that trip: st.file_uploader brings a file in, and st.download_button sends one out. In between you use ordinary pandas.

This lesson covers both widgets, how to read the common formats, how to validate what a stranger uploaded, and how to keep the app fast with large files. If you are new to pandas, the pandas tutorial explains DataFrames in detail.

Streamlit cannot run on this site. The app code below is read-only. The runnable examples use io.StringIO and io.BytesIO objects, which behave exactly like the file objects Streamlit gives you, so the pandas code in them is real.

st.file_uploader

Python
import pandas as pd
import streamlit as st

uploaded = st.file_uploader("Upload a CSV file", type=["csv"])

if uploaded is None:
    st.info("Upload a file to begin.")
    st.stop()

df = pd.read_csv(uploaded)
st.write(f"{len(df)} rows, {len(df.columns)} columns")
st.dataframe(df.head(20))

Until the user picks a file, file_uploader returns None. Guarding with st.stop() keeps the rest of the script from running on missing data (see How Streamlit Reruns Your Script).

The returned UploadedFile is a subclass of io.BytesIO. It has .name, .type (MIME type) and .size (bytes), and works anywhere a binary file object is accepted: pd.read_csv, pd.read_excel, json.load, PIL.Image.open, zipfile.ZipFile and more. Useful parameters:

Parameter Purpose
type Allowed extensions: ["csv", "xlsx"]. A filter in the browser, not a security check
accept_multiple_files True returns a list of files
key Identity and session state key
help Tooltip text

The default upload limit is 200 MB per file, and can be changed with server.maxUploadSize in config.toml (see Configuration and Themes).

Reading a CSV safely

Uploaded files are unpredictable: wrong delimiter, a different encoding, missing columns, numbers stored as text. Wrap the read in try and report problems in plain language. This stand-in does the validating part with a real pandas read from an in-memory file.

Python Reading and validating an uploaded CSV

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The good file loses one row with an invalid date; the bad file is rejected with a clear list of missing columns. In a real app the message goes to st.error or st.warning, followed by st.stop().

Excel, JSON and other formats

The same pattern works for other types, picking the reader by extension:

Python
import json
import pandas as pd

def read_any(uploaded):
    name = uploaded.name.lower()
    if name.endswith(".csv"):
        return pd.read_csv(uploaded)
    if name.endswith((".xlsx", ".xls")):
        return pd.read_excel(uploaded, sheet_name=0)    # needs openpyxl installed
    if name.endswith(".json"):
        return pd.json_normalize(json.load(uploaded))
    if name.endswith(".parquet"):
        return pd.read_parquet(uploaded)                # needs pyarrow
    raise ValueError("Unsupported file type")

Excel needs the openpyxl package (for .xlsx), which you list in requirements.txt. Workbooks have several sheets: pd.ExcelFile(uploaded).sheet_names gives the names, and a st.selectbox lets the user pick one:

Python
book = pd.ExcelFile(uploaded)
sheet = st.selectbox("Sheet", book.sheet_names)
df = book.parse(sheet)

For text files, uploaded.getvalue().decode("utf-8") returns a string, and uploaded.read() returns bytes (remember that after one read() the pointer is at the end; call uploaded.seek(0) before reading again, which is a common reason for a mysterious empty DataFrame on a rerun).

Multiple files

Python
files = st.file_uploader("Upload CSVs", type="csv", accept_multiple_files=True)
if files:
    frames = [pd.read_csv(f).assign(source=f.name) for f in files]
    combined = pd.concat(frames, ignore_index=True)
    st.dataframe(combined)

assign(source=f.name) records which file each row came from, a useful habit when combining uploads.

Cache parsing, not the widget

The file uploader keeps the file in memory, and every rerun gives you the same bytes. Parsing a large CSV on every slider move is slow, so cache the parse keyed by the file content:

Python
@st.cache_data
def parse(file_bytes: bytes) -> pd.DataFrame:
    return pd.read_csv(io.BytesIO(file_bytes))

df = parse(uploaded.getvalue())

Passing getvalue() (bytes) works because bytes are hashable. Passing the UploadedFile object itself would not be a stable key. See Caching for the rules.

st.download_button

st.download_button lets users save data from the app. It needs the data to be a string or bytes:

Python
csv_bytes = result.to_csv(index=False).encode("utf-8")
st.download_button(
    label="Download cleaned data",
    data=csv_bytes,
    file_name="cleaned.csv",
    mime="text/csv",
)

Clicking it triggers a rerun like any widget, although the download itself comes from the data you passed when the page was drawn. For large results, compute the bytes inside a cached function so they are not rebuilt on every rerun. For Excel output write to a BytesIO with pd.ExcelWriter (again needs openpyxl), and for images use fig.savefig(buffer, format="png").

Build the download content next. This TryIt produces the CSV and JSON bytes that would be handed to the button, including a round trip to prove the data is intact.

Python Building download bytes with pandas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In an app, csv_bytes goes to st.download_button(data=csv_bytes, file_name="sales.csv", mime="text/csv").

Show the table: a preview

After loading, show enough for users to trust the upload without flooding the page:

Python
st.write(f"{len(df):,} rows ร— {len(df.columns)} columns")
st.dataframe(df.head(100), use_container_width=True)
st.write(df.describe(include="all").T)
st.write(df.isna().sum().rename("missing values"))

st.dataframe is interactive (sort, resize, search); st.table is static and best for short tables.

Safety notes

  • type= is only a hint. Check what you actually parse, and catch parser errors.
  • Never eval or exec anything from an uploaded file. Never unpickle an uploaded file (pd.read_pickle, pickle.load) because pickles can run code.
  • Do not use the uploaded file's name to build a path on disk without cleaning it. Use your own generated name.
  • Remember files are in memory. Large uploads from many users add up; set a sensible server.maxUploadSize.

Common mistakes

  • Reading the same UploadedFile twice without seek(0).
  • Parsing the file on every rerun instead of caching on getvalue().
  • Passing a DataFrame to download_button instead of bytes.
  • Forgetting openpyxl in requirements.txt for Excel.
  • Trusting the extension and unpickling user files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does st.file_uploader return before the user chooses a file?

    It returns None until a file is uploaded, so check for None and use st.stop() or an info message.
  2. 2. Which data types can st.download_button accept for its data argument?

    Convert first: df.to_csv(...).encode(), json.dumps(...), or a BytesIO buffer.
  3. 3. Why call uploaded.getvalue() before a cached parse function?

    Bytes are hashable and identical content produces the same key, so repeated reruns skip the parse.
  4. 4. Which is unsafe to do with an uploaded file?

    Pickle can execute arbitrary code during loading. Never unpickle data from users.

Summary

  • st.file_uploader returns None or an UploadedFile, a binary file object that pandas and other readers accept.
  • Validate columns and types, and report problems with st.error followed by st.stop().
  • Cache parsing with getvalue() bytes as the key; call seek(0) before rereading a file.
  • st.download_button needs string, bytes or file-like data; build it with to_csv(...).encode().
  • Excel needs openpyxl; never unpickle uploads.

Next: SQL Databases and st.connection