How to retrieve a file saved using openpyxl in streamlit app?

Hello there !

I have a python code that calculates a file with excel format, and I usually save it with openpyxl using the command : workbook.save(filename) when I work in local.

Now, I want to do the same thing using streamlit. The file “workbook” is calculated alright, but I do not succeed in retrieving it using a download button, here is what I am doing so far :

st.download_button(“Récupérer le fichier”,
data=workbook,
mime=‘xlsx’,
file_name=“coucou.xlsx”)

but the format is invalid. I have tried to convert in Dataframe using Pandas and convert in binary but no success so far…

Or alternatively, would it be possible to save the file using openpyxl as I do in local, and then retrieve it from the streamlit buffer ?

Thanks and best wishes for your day

Hello there, I have finally found a workaround ! So here I share it with the community :slight_smile:

from openpyxl import Workbook
from io import BytesIO

workbook = Workbook()

with NamedTemporaryFile() as tmp:
     workbook.save(tmp.name)
     data = BytesIO(tmp.read())

st.download_button("Retrieve file",
     data=data,
     mime='xlsx',
     file_name="name_of_file.xlsx")