Reputation: 91
I want to know if there is any way to download the output dataframe of streamlit as an Excel file using the streamlit button?
Upvotes: 4
Views: 9458
Reputation: 21
Small improvement to the solution provided by edesz:
preparing the Excel only after prepare-button is clicked and added the required writer.close()
def excel_download_buttons(df: pd.DataFrame, file_name: str = "export.xlsx") -> None:
"""Show prepare data and download buttons."""
if st.button("Click to prepare download"):
buffer = io.BytesIO()
with pd.ExcelWriter(buffer, engine="xlsxwriter") as writer:
df.to_excel(writer, sheet_name="Sheet1", index=False)
writer.close()
st.download_button(
label="Download data as Excel",
data=buffer,
file_name=file_name,
mime="application/vnd.ms-excel",
)
Upvotes: 0
Reputation: 464
I suggest you edit your question to include a minimal reproducible example so that it's easier for people to understand your question and to help you.
Here is the answer if I understand you correctly. Basically it provides 2 ways to download your data df
as either csv or xlsx.
IMPORTANT: You need to install xlsxwriter
package to make this work.
import streamlit as st
import pandas as pd
import io
# buffer to use for excel writer
buffer = io.BytesIO()
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45],
"random1": [5, 12, 1],
"random2": [230, 23, 1]
}
df = pd.DataFrame(data)
@st.cache
def convert_to_csv(df):
# IMPORTANT: Cache the conversion to prevent computation on every rerun
return df.to_csv(index=False).encode('utf-8')
csv = convert_to_csv(df)
# display the dataframe on streamlit app
st.write(df)
# download button 1 to download dataframe as csv
download1 = st.download_button(
label="Download data as CSV",
data=csv,
file_name='large_df.csv',
mime='text/csv'
)
# download button 2 to download dataframe as xlsx
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
# Write each dataframe to a different worksheet.
df.to_excel(writer, sheet_name='Sheet1', index=False)
download2 = st.download_button(
label="Download data as Excel",
data=buffer,
file_name='large_df.xlsx',
mime='application/vnd.ms-excel'
)
Upvotes: 8