aiogram 将 excel 文件作为文件下载给用户

问题描述 投票:0回答:1

我有一个小项目,是用电报自动化工作任务。 我用的是aiogram 3.5版本

  1. 我需要上传excel文件,其中包含几张工作表作为字典,工作表名称作为字典键,它们的信息作为pandas数据框。
  2. 对其上的字典和数据帧进行操作。
  3. 更新、改变的dict需要写回excel文件,并发送给用户 我在第三个任务中遇到问题。我找不到如何写入并将写入的文件发送给用户的方法。 附言。新的 excel 文件应该是临时的。我不需要从服务器存储额外的存储空间。 我提供代码,如果有一些建议或建议,请提供解决方案。分享它。谢谢你的提前。
#function for write updated excel_data dict to excel
def process_excel_data_to_bytesio():
    try:
        # Create a BytesIO buffer
        buffer = io.BytesIO()

        # Write the updated DataFrames to the buffer
        with pd.ExcelWriter(buffer, engine='openpyxl') as writer:
            for sheet_name, df in excel_data.items():
                df.to_excel(writer, sheet_name=sheet_name, index=False)
                print(f"{sheet_name} is written")
        # Seek to the beginning of the stream
        buffer.seek(0)
        return buffer
    except Exception as e:
        logging.error(f"Error processing Excel file: {e}")
        return None

@file_router.callback_query(F.data == "download_ip_file")
async def download_updated_ipfile_touser(query: CallbackQuery):
    try:
        if is_admin(query.from_user.id):
            await query.answer("📎📊📈 Faylni serverdan qabul qilib oling\n yuklanmoqda...", reply_markup=ReplyKeyboardRemove())

            # Process the Excel data to a BytesIO object
            buffer = process_excel_data_to_bytesio()
            await query.message.answer("ok", reply_markup=ReplyKeyboardRemove())

            # Check if the buffer was processed successfully
            if buffer is not None:
                # Send the processed file to the user
                with open('updated.xlsx', 'wb') as file:
                    file.write(buffer.getvalue())
                await query.message.answer("faylga yozildi", reply_markup=ReplyKeyboardRemove())

                await bot.send_document(chat_id=query.from_user.id, document=open('updated.xlsx', 'rb'))
                await query.message.answer("fayl yuborildi", reply_markup=ReplyKeyboardRemove())
                file_downloaded(user_id=query.from_user.id, user_firstname=query.from_user.first_name)
            else:
                await query.message.reply("❌ Faylni yozishda xatolik yuz berdi")
        else:
            await query.answer("🚫Siz admin emassiz, fayl yuklolmaysiz!", reply_markup=ReplyKeyboardRemove())
    except Exception as e:
        await query.message.reply(f"❌❓Возникло ошибка ! : <b>{str(e)}</b>\n")

当用户点击按钮以获得更新的文件时,他们应该通过提供更新的Excel文件来服务

pandas openpyxl aiogram bytesio
1个回答
0
投票

解决方案已找到。

#ozgartirilgan excel_data dict ni yangi excel fayl yaratib,foydalanuvchiga yuborish hendleri @file_router.callback_query(lambda c: c.data == "download_ip_file") 异步 def download_ip_file(查询: CallbackQuery): 尝试: 如果 is_admin(query.from_user.id): 等待查询.answer("📎📊📈 Faylni serverdan qabul qilib oling 尤克兰莫克达...", reply_markup=ReplyKeyboardRemove()) file_path = f'ip_plan_file{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.xlsx'

        # Write the DataFrames to the Excel file
        with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
            for sheet_name, df in excel_data.items():
                df.to_excel(writer, sheet_name=sheet_name, index=False)

        # Check if the file was processed successfully
        if file_path is not None and os.path.exists(file_path):
            # Send the processed file to the user
            # Fetch the action before sending the file
            await query.bot.send_chat_action(
                chat_id=query.message.chat.id,
                action=ChatAction.UPLOAD_DOCUMENT,
            )
            await bot.send_document(query.from_user.id, BufferedInputFile.from_file(file_path))

             # Remove the file after sending it
            os.remove(file_path)

            file_downloaded(user_id=query.from_user.id, user_firstname=query.from_user.first_name)
        else:
            await query.message.reply("❌ Faylni yozishda xatolik yuz berdi")
    else:
        await query.answer("🚫Siz admin emassiz, fayl yuklolmaysiz!", reply_markup=ReplyKeyboardRemove())
        await query.message.answer("🚫Siz admin emassiz, fayl yuklolmaysiz!", reply_markup=ReplyKeyboardRemove())
except Exception as e:
    logging.error(f"An error occurred: {str(e)}")
    await query.message.reply(f"❌❓Возникло ошибка ! : <b>{str(e)}</b>\n")
finally:
    # Always remove the file after the operation
    if os.path.exists(file_path):
        os.remove(file_path)
        logging.info("Temporary file deleted.")
        await query.message.answer("Temporary file deleted.", reply_markup=ReplyKeyboardRemove())
© www.soinside.com 2019 - 2024. All rights reserved.