gpt4 book ai didi

python-3.x - Flask-Pandas 创建下载文件

转载 作者:行者123 更新时间:2023-12-03 16:03:00 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Writing then reading in-memory bytes (BytesIO) gives a blank result

(2 个回答)


4年前关闭。




我有一个小应用程序,我在其中输入了一些 csv 文件,使用 Pandas 进行了一些数据处理,最终我希望在完成后将结果吐出一个 excel 文件。

现在我可以将处理结果呈现为 html,并且我有一个表格正在运行。但是,当我尝试创建要下载的 excel 文件时,问题就出现了。

下面是获取数据框并创建 excel 文件的代码部分。

进口:

from flask import Flask, request, render_template, send_file
from io import BytesIO
import pandas as pd

.
. Stuff
.

output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
xlsx_data = output.getvalue()

return send_file(xlsx_data, attachment_filename='output.xlsx', as_attachment=True)

它下载但它是 0kb,我在 excel 中得到以下内容, Excel Cannot open the file 'output.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
这是什么问题?

使用 python 3.6

最佳答案

您需要seek写入内存文件中的初始文件后,回到文件的开头。不需要 xlsx_data多变的:

# ...
writer.save()
output.seek(0)
return send_file(output, attachment_filename='output.xlsx', as_attachment=True)


Writing then reading in-memory bytes (BytesIO) gives a blank result

关于python-3.x - Flask-Pandas 创建下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42809592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com