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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With