Downloading a MS Word document

I have an app that allows to edit an uploaded Word document. The edits would need to be saved as a separate document and then saved. To accomplish this I use the st.download_button. However, when I run the code I get this error: RuntimeError: Invalid binary data format: <class ‘NoneType’>. And this one as well: RuntimeError(“Invalid binary data format: %s” % type(data)).

Why do these errors occur? Any form of help would be appreciated.

I am using Python 3.10.4, Streamlit 1.11.1, Virtualenv, PyCharm Community Edition 2022.1.4, Windows 11, Firefox 103.0.1 (64-bit).

My code for the download button is shown here:

st.download_button(label='Download Edits', data=edited_doc, file_name='EDITED.docx', mime='application/octet-stream', key=321)

2 Likes

if you find a solution pls tell

Python-docx’s method accepts a stream instead of a filename. Thus, you can initialize an io.BytesIO() object to save the document into, then dump that to the user.

I have tried this and it worked for me

    import io
    doc_download = doc_file_creation(doc_file)

    bio = io.BytesIO()
    doc_download.save(bio)
    if doc_download:
        st.download_button(
            label="Click here to download",
            data=bio.getvalue(),
            file_name="Report.docx",
            mime="docx"
        )
2 Likes

Hi Kiran I am looking for a solution like this. From which module is the function ‘doc_file_creation’?

1 Like

Hi TorOEkle

doc_file_creation is just a function name which I used for returning an already created word document. You can use docx or docxtpl modules for creating a docx file.

2 Likes

Your trick worked great ! Thanks Kiran !

1 Like

Works🔥
Thank you