Export and download dataframe to csv file

Hi, I’m trying to export and download a dataframe to a .csv file with the function:

> def get_table_download_link_csv(df):
>     csv = df.to_csv(index=False)
>     b64 = base64.b64encode(csv.encode()).decode() 
>     href = f'<a href="data:file/csv;base64,{b64}" download="download.csv">Download csv file</a>'
>     return href

The function works great in my local machine, but when I publish the app in Streamlit Share, the function doesn’t work properly and when I click in the link nothing happends. I noticed that when I right click on the link and select “save link as” the file is downloaded with the defined name.

I tried to add the “target=”_blank" attribute, and it works correctly only if the file name is not specified, but I think that this is not the most usable for the user, since the file is downloaded without a specific extension.

Thanks for the support

try this. hope helps

csv = df.to_csv().encode()

b64 = base64.b64encode(csv).decode()

href = f’Download CSV File

st.markdown(href, unsafe_allow_html=True)

Hi @abbmimn, thanks for your reply. I try with your code and it works perfectly in my local machine, but when I publish the app in Share Streamlit the file doesn’t download. I think theres is a little bug because when I add the atribbute “target=_blank” the file downloads, but with no name, and when I add the attribute “download=filename.csv” to define the download name, the file not download.

This is my code modified with your suggested code:

The function:

def get_table_download_link_csv(df):
    #csv = df.to_csv(index=False)
    csv = df.to_csv().encode()
    #b64 = base64.b64encode(csv.encode()).decode() 
    b64 = base64.b64encode(csv).decode()
    href = f'<a href="data:file/csv;base64,{b64}" download="captura.csv" target="_blank">Download csv file</a>'
    return href

The call of the function:
st.markdown(get_table_download_link_csv(df), unsafe_allow_html=True)

Thanks again