Thanks for the useful replies and cross post linking everyone!
I got my Excel file download working with a combination of openpyxl, using wb.save("test.xlsx") to save it to the current app dir and then jamming that file into: file = f'<a href="test.xlsx" download="test.xlsx">Download excel file</a>'
and using st.markdown(file, unsafe_allow_html=True) to actually show a download link.
I use a regular st.button to generate the new Excel file and then the markdown link to download gets generated underneath it.
I wish Streamlit would add a great looking download button like the one that you posted feliperoque
It’s a bit weird that we’ve had the file_uploader widget for quite some time but no nice button to download files(and no way to link a regular st.button to download a file).
Might have to find some time to learn how those UI components are built in Streamlit so I can try to build one.
Hi @snehankekre, thanks a lot for this solution. Can you please help me with understadning, how to add multiple sheets in the excel file and then download that. With your current code, I checked, only one sheet is getting added. Thanks
Certainly. I’ll show you how to use st.download_button to do the job. You’ll have to install the xlsxwriter package and/or add it to your requirements file.
import streamlit as st
import pandas as pd
import io
buffer = io.BytesIO()
# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
df3.to_excel(writer, sheet_name='Sheet3')
# Close the Pandas Excel writer and output the Excel file to the buffer
writer.save()
st.download_button(
label="Download Excel worksheets",
data=buffer,
file_name="pandas_multiple.xlsx",
mime="application/vnd.ms-excel"
)
Thank you very much for your code. I do have a question regarding the buffer.
I am trying to have 6 streamlit download buttons. Each button has 5 dataframes that it needs to save.
The first download button does the job well. But the second download button with 5 other dataframes doesn’t work properly. It still shows data from the previous button. Could you help me out what is going on here?
Do I have to write a function to reset the buffer?
You’ll need to create a new buffer and writer per download button. So, in your case 6 buffers and 6 writers. Do this by copying the code shown by @snehankekre multiple times, or with a bit more organization, you can wrap it in an object/class and reuse the class 6 times.