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

基于aiogram 3.5实现临时Excel文件生成与发送的问题求助

解决aiogram 3.5内存生成Excel并发送的问题

核心方案

利用io.BytesIO在内存中创建临时Excel文件,无需服务器存储,直接通过Telegram API发送。以下是完整实现代码及注意事项:

代码实现

导入依赖

import io
import pandas as pd
from aiogram import Bot
from aiogram.types import FSInputFile

内存生成并发送Excel函数

async def send_edited_excel(bot: Bot, chat_id: int, processed_data: dict):
    # 初始化内存文件对象
    excel_buffer = io.BytesIO()
    
    # 将字典中的DataFrame写入多工作表Excel
    with pd.ExcelWriter(excel_buffer, engine="openpyxl") as writer:
        for sheet_name, df in processed_data.items():
            df.to_excel(writer, sheet_name=sheet_name, index=False)
    
    # 重置文件指针至起始位置,避免发送空文件
    excel_buffer.seek(0)
    
    # 包装内存文件为aiogram可识别的输入对象
    file_to_send = FSInputFile(excel_buffer, filename="处理完成的文件.xlsx")
    
    # 发送文档给用户
    await bot.send_document(chat_id=chat_id, document=file_to_send)

调用示例

在你的消息处理流程中,完成DataFrame修改后调用上述函数:

# 示例:已处理完成的工作表字典
processed_df_dict = {
    "销售数据": pd.DataFrame({"日期": ["2024-01-01", "2024-01-02"], "金额": [1000, 1500]}),
    "库存数据": pd.DataFrame({"商品": ["A", "B"], "库存": [50, 30]})
}

# 在消息处理函数内调用
await send_edited_excel(bot, message.chat.id, processed_df_dict)

关键注意事项

  • 文件指针重置:写入Excel后必须执行excel_buffer.seek(0),否则读取的是文件末尾的空内容。
  • 引擎依赖:确保安装openpyxl库(pandas写入xlsx格式的必需引擎),执行pip install openpyxl完成安装。
  • aiogram 3.x适配:使用FSInputFile处理内存文件,该类支持传入BytesIO对象,无需本地文件路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 09:19:57