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

如何导出Streamlit extras dataframe explorer的筛选结果至Excel

导出DataFrame Explorer筛选结果至Excel的方案

核心原理

dataframe_explorer(df)返回的变量就是经过UI筛选/选择后的最终DataFrame,不需要额外捕获筛选状态,直接基于这个变量做导出即可。

实现步骤

  1. 先安装Excel导出依赖:
pip install openpyxl

pandas导出xlsx格式需要依赖openpyxl,必须提前安装。

  1. 修改你的代码,添加下载按钮逻辑:
import streamlit as st
from streamlit_extras.dataframe_explorer import dataframe_explorer
import pandas as pd
from io import BytesIO

# 替换成你的原始DataFrame加载逻辑
df = pd.read_csv("your_source_data.csv")

# 获取筛选后的DataFrame
df_filtered = dataframe_explorer(df)

# 展示筛选结果
st.dataframe(df_filtered)

# 定义Excel转换函数
def convert_to_excel(df):
    output = BytesIO()
    with pd.ExcelWriter(output, engine="openpyxl") as writer:
        df.to_excel(writer, index=False, sheet_name="筛选数据")
    output.seek(0)
    return output

# 添加下载按钮
excel_file = convert_to_excel(df_filtered)
st.download_button(
    label="下载筛选结果为Excel",
    data=excel_file,
    file_name="筛选后数据.xlsx",
    mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)

关键说明

  • 直接使用dataframe_explorer返回的df_filtered,它已经包含了所有UI操作后的结果
  • convert_to_excel函数将DataFrame转为字节流,适配Streamlit下载按钮的要求
  • 设定正确的mime类型,确保浏览器识别为Excel文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:40:18