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

标签 python-3.x pandas flask

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





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/

相关文章:

python - 使用 Python 删除所有匹配正则表达式的行

python - Gunicorn 不会启动 Flask 应用程序,因为 "Application object must be callable"

python - 仅在 Flask 应用程序中显示未分类的消息

python - 仅在具有多索引的系列的一层上使用 agg 方法

python - Popen/Wait - 等待永远不会结束

python - 如何将列表列表转换为第一个元素是索引,第二个是列名的数据框

python - 在 Pandas 中跨多个列应用 map

python - Flask - 获取 session 的查询结果

python - 将两个多维列表合并为一个列表

python - 使用 panda 连接 2 个 csv 文件且不包含行索引