Flask-Pandas Creating a download file [duplicate]

穿精又带淫゛_ 提交于 2020-08-02 04:23:13

问题


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.

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.

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

Imports:

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)

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.

What's is the issue?

using python 3.6


回答1:


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)

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



来源:https://stackoverflow.com/questions/42809592/flask-pandas-creating-a-download-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!