You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit下载DataFrame为CSV格式异常的问题咨询

问题原因
  • 自定义下载链接中使用的file/csv不是CSV文件的标准MIME类型,浏览器无法将资源识别为CSV格式
  • a标签未添加download属性指定默认存储文件名,导致浏览器默认将文件保存为无后缀的对象文件
修复方案1:修改原有自定义链接代码

只需调整href属性中的MIME类型,同时添加download属性指定CSV文件名即可,修改后的完整代码如下:

import pandas as pd
import base64
import streamlit as st

X = pd.DataFrame({'A':["bad",  "good", "better",   "good", "better",   "good", "better",   "good", "better",   "bad",  "good", "better",   "good", "better",   "bad",  "good", "better",   "bad",  "good", "better",   "good", "better",   "bad"],
                   'B': [3803,  1062,   4862,   6356,   2171,   532,    6982,   891,    1961,   3631,   1626,   1507,   3069,   2793,   721,    4288,   1601,   1439,   5807,   5054,   2411,   2913,   3505],
                   'C': [1318,  2537,   2315,   4967,   4483,   1433,   529,    1262,   1583,   506,    2576,   289,    3740,   3087,   309,    3493,   1862,   2666,   1231,   1828,   4144,   3503,   3102]
})

if X is not None:
    csv_exp = X.to_csv(index=False)
    b64 = base64.b64encode(csv_exp.encode()).decode()
    # 调整MIME类型为text/csv,添加download属性指定文件名
    href = f'<a href="data:text/csv;base64,{b64}" download="预测结果.csv">下载预测文件</a>(右键另存为csv)'
    st.markdown(href, unsafe_allow_html=True)
修复方案2:使用Streamlit原生下载按钮(更稳定,无需手动处理编码)

Streamlit 0.88及以上版本已经内置了下载按钮组件,无需手动编写HTML和base64编码逻辑,使用更简单兼容性更好:

import pandas as pd
import streamlit as st

X = pd.DataFrame({'A':["bad",  "good", "better",   "good", "better",   "good", "better",   "good", "better",   "bad",  "good", "better",   "good", "better",   "bad",  "good", "better",   "bad",  "good", "better",   "good", "better",   "bad"],
                   'B': [3803,  1062,   4862,   6356,   2171,   532,    6982,   891,    1961,   3631,   1626,   1507,   3069,   2793,   721,    4288,   1601,   1439,   5807,   5054,   2411,   2913,   3505],
                   'C': [1318,  2537,   2315,   4967,   4483,   1433,   529,    1262,   1583,   506,    2576,   289,    3740,   3087,   309,    3493,   1862,   2666,   1231,   1828,   4144,   3503,   3102]
})

if X is not None:
    csv_exp = X.to_csv(index=False).encode('utf-8')
    st.download_button(
        label="下载预测文件",
        data=csv_exp,
        file_name="预测结果.csv",
        mime="text/csv"
    )

内容的提问来源于stack exchange,提问作者Yogesh Govindan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 14:45:02