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

Streamlit应用实操:如何让用户在应用内点击按钮下载Excel文件

解决方案

分两种常用场景实现:

场景1:已有本地现成Excel文件

csv示例用的是默认文本读取模式,Excel属于二进制文件,必须用二进制读模式rb打开,这是直接套用csv代码失效的核心原因。

import streamlit as st

# 注意打开模式为二进制读取'rb'
with open("你的本地Excel文件路径.xlsx", "rb") as f:
    st.download_button(
        label="点击下载Excel文件",
        data=f,
        file_name="导出结果.xlsx",
        mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )

补充说明:mime参数用于指定文件格式类型,避免浏览器识别错误导致下载的文件后缀异常。

场景2:直接通过DataFrame生成Excel,无需存本地

直接调用pd.to_excel()不传路径参数时,默认返回None,内容不会直接输出,需要借助BytesIO做内存缓存承接Excel内容,这是直接传pd.to_excel()返回值失效的原因。

import streamlit as st
import pandas as pd
from io import BytesIO

# 替换为你自己的DataFrame
df = pd.DataFrame({
    "示例列1": [1, 2, 3, 4],
    "示例列2": ["内容A", "内容B", "内容C", "内容D"]
})

# 初始化内存缓存对象
buffer = BytesIO()

# 将DataFrame写入缓存
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
    df.to_excel(writer, index=False, sheet_name="数据Sheet")

# 将缓存读取指针移到开头,否则下载会拿到空文件
buffer.seek(0)

st.download_button(
    label="点击下载Excel文件",
    data=buffer,
    file_name="导出结果.xlsx",
    mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)

补充说明:如果只需要导出单Sheet,也可以简化写为df.to_excel(buffer, index=False),不需要显式调用ExcelWriter,写完后同样需要执行buffer.seek(0)。

内容的提问来源于stack exchange,提问作者b.dot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:57:00