Flask-Pandas创建下载文件 [英] Flask-Pandas Creating a download file

查看:108
本文介绍了Flask-Pandas创建下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a small app where I input a few csv files, do some data processing with pandas and eventually I would like to have the results spit out an excel file once it is done.

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

Right now I can render the results of the processing to html and I have a table up and running. However the issues comes when I try to create an excel file for download.

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

Below is the section of code that takes the dataframe and creates the excel file.

进口:

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由于文件格式或文件扩展名无效,因此无法打开文件'output.xlsx'.确认文件未损坏,并且文件扩展名与文件格式匹配.

It downloads but its 0kb and I get the following in 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

using python 3.6

推荐答案

在将初始文件写入内存文件后,需要 seek 回到文件的开头.而且不需要 xlsx_data 变量:

You need to seek back to the beginning of the file after writing the initial in memory file. And no need for the xlsx_data variable:

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

请参阅写然后读的内存字节(BytesIO)给出空白结果

这篇关于Flask-Pandas创建下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆