st.download_button widget in Streamlit
The download_button widget is used to display a download button in a Streamlit app. This is useful when you want to provide a way for users to download a file directly from your application.
Basic Syntax
st.download_button(
label="Download",
data="This is some text to download.",
file_name="example.txt",
mime="text/plain"
) The function has the following parameters:
- label — Text shown on the button.
- data — The content to be downloaded (string, bytes, or file-like object).
- file_name — Default name of the downloaded file.
- mime — MIME type (e.g., "text/plain", "text/csv", "application/pdf").
When the user clicks the button, the browser automatically downloads the file.
Example: Download a CSV file from a DataFrame.
Python
import streamlit as st
import pandas as pd
# Create sample data
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Score": [85, 90, 78]
}
# Create DataFrame
df = pd.DataFrame(data)
# Filter rows where Score >= 80
newdf = df[df["Score"] >= 80]
# Display filtered DataFrame
st.write(newdf)
# Convert DataFrame to CSV format
csv_data = newdf.to_csv(index=False)
# Create download button
st.download_button(
label="📥 Download CSV",
data=csv_data,
file_name="student_scores.csv",
mime="text/csv"
) Explanation
- df.to_csv() converts the DataFrame into a CSV string.
- st.download_button() allows users to download the file instantly.