Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Pandas Creating a download file [duplicate]

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

like image 858
spitfiredd Avatar asked Mar 15 '17 12:03

spitfiredd


1 Answers

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

like image 159
td39 Avatar answered Oct 22 '22 11:10

td39