Download html files


I want to create a button that downloads an html leafmap file (I have a map on my app and I use map.to_html()),
I want to avoid Re-run when pressing the button .
I have a code for such a button for Excel files, but i don’t manage to update it to html files.
Please help :slight_smile:

Steps to reproduce

Code snippet:

def create_button():
    button_uuid = str(uuid.uuid4()).replace('-', '')
    button_id = re.sub('\d+', '', button_uuid)
    custom_css = f""" 
                #{button_id} {{
                display: inline-flex;
                align-items: center;
                justify-content: center;
                background-color: #52835d;
                color: rgb(38, 39, 48);
                padding: .25rem .75rem;
                position: relative;
                text-decoration: none;
                border-radius: 4px;
                border-width: 1px;
                border-style: solid;
                border-color: rgb(230, 234, 241);
                border-image: initial;
                #{button_id}:hover {{
                    border-color: rgb(246, 51, 102);
                    color: rgb(246, 51, 102);
                #{button_id}:active {{
                    box-shadow: none;
                    background-color: rgb(246, 51, 102);
                    color: white;
            </style> """
    return button_id, custom_css

def save_file(df: pd.DataFrame, file_name, label="Download excel File"):
    output = io.BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    df.to_excel(writer, sheet_name="Sheet1", startrow=0, startcol=0, index=False)
    b64 = base64.b64encode(output.getvalue()).decode()  # some strings <-> bytes conversions necessary here
    button_id, custom_css = create_button()
    href = custom_css + f'<a href="data:file/xlsx;base64,{b64}" id="{button_id}" download="{file_name}.xlsx">' \
    return href
1 Like

Hi @Dekel_K

Streamlit has a st.download_button that allows the saving of files upon clicking on the button.

Example code snippet is also provided in the st.download_button Streamlit Docs page.

1 Like