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

如何修改Python代码生成含多Sheet Excel文件的HTML下载链接?

解决方案

要生成包含多个DataFrame(对应不同工作表)的xlsx文件下载链接,你需要处理二进制的Excel文件流,而非像CSV那样直接处理文本。以下是修改后的代码:

import base64
import io
import pandas as pd
from IPython.display import HTML

def create_xlsx_download_link(df_dict, title="Download Excel file", filename="case_review.xlsx"):
    # 创建内存字节流对象,无需写入本地文件
    output = io.BytesIO()
    
    # 通过ExcelWriter将多个DataFrame写入对应工作表
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        for sheet_name, df in df_dict.items():
            df.to_excel(writer, sheet_name=sheet_name, index=False)
    
    # 将字节流指针移至起始位置,准备读取内容
    output.seek(0)
    
    # 对Excel文件内容进行base64编码
    b64 = base64.b64encode(output.read()).decode()
    
    # 构造xlsx格式对应的Data URI下载链接
    html = f'<a download="{filename}" href="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,{b64}" target="_blank">{title}</a>'
    
    return HTML(html)

# 示例用法:传入字典,键为工作表名,值为对应DataFrame
# df_dict = {"用户表": user_df, "订单表": order_df, "商品表": product_df}
# create_xlsx_download_link(df_dict)

关键说明:

  • 用io.BytesIO在内存中生成Excel文件,省去本地存储或S3上传的繁琐流程
  • 依赖openpyxl引擎实现多工作表写入,需确保已安装该库(可通过pip install openpyxl安装)
  • 指定正确的MIME类型application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,保证浏览器识别xlsx格式
  • 采用字典参数关联工作表名与DataFrame,更直观地管理多表内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:05:51