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

如何在Streamlit中将Pandas DataFrame下载为CSV文件

Streamlit大体积DataFrame导出为CSV的实现方案

基础实现方法

核心通过st.download_button绑定DataFrame转码后的CSV字节流实现下载,同时加缓存避免重复计算,适配大文件场景:

import streamlit as st
import pandas as pd

# 你的大体积DataFrame,此处替换为你实际的DF变量
large_df = xxx

# 加缓存装饰器,避免每次点击下载都重新转码,大幅提升大文件处理速度
@st.cache_data
def convert_df_to_csv(df):
    # 使用utf_8_sig编码,导出的CSV直接用Excel打开不会出现中文乱码
    # index=False代表不导出pandas自带的行索引,需要保留的话删除该参数即可
    return df.to_csv(index=False, encoding='utf_8_sig').encode('utf-8')

csv_bytes = convert_df_to_csv(large_df)

# 渲染下载按钮
st.download_button(
    label="下载CSV数据文件",
    data=csv_bytes,
    file_name="导出业务数据.csv",
    mime="text/csv"
)

超大体量DataFrame优化方案

如果你的DataFrame体积超过500MB,建议先压缩为ZIP格式再提供下载,减少传输时间和内存占用:

import streamlit as st
import pandas as pd
import io
import zipfile

large_df = xxx

@st.cache_data
def convert_df_to_zipped_csv(df):
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
        csv_content = df.to_csv(index=False, encoding='utf_8_sig')
        zip_file.writestr("导出业务数据.csv", csv_content)
    return zip_buffer.getvalue()

zipped_csv = convert_df_to_zipped_csv(large_df)

st.download_button(
    label="下载压缩包格式CSV数据",
    data=zipped_csv,
    file_name="导出业务数据.zip",
    mime="application/zip"
)

注意事项

  • 导出前可提前删除不需要的字段,进一步缩小生成的文件体积
  • Streamlit默认文件大小限制为200MB,若导出文件超过该阈值,启动应用时添加参数调整上限即可:streamlit run 你的应用文件名.py --server.maxUploadSize=2048,数值单位为MB,可按需调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:39:02