Reputation: 2955
I am reusing some code posted here Excel export with Flask server and xlsxwriter:
import numpy as np
import pandas as pd
from io import BytesIO
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/')
def index():
#create a random Pandas dataframe
df_1 = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))
#create an output stream
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
#taken from the original question
df_1.to_excel(writer, startrow = 0, merge_cells = False, sheet_name = "Sheet_1")
workbook = writer.book
worksheet = writer.sheets["Sheet_1"]
format = workbook.add_format()
format.set_bg_color('#eeeeee')
worksheet.set_column(0,9,28)
#the writer has done its job
writer.close()
#go back to the beginning of the stream
output.seek(0)
#finally return the file
return send_file(output, attachment_filename="testing.xlsx", as_attachment=True)
app.run(debug=True)
I am running Ubuntu 18 and my code sits in a docker container. Unfortunately this code doesn't download an xlsx file. It downloads an entire archive, e.g. with subfolders etc. Hence I played with the mimetype in send_file but no success. What could be wrong with my setup. Funny enough I can open the archive directly in LibreOffice Calc and I get the worksheets I was expecting to see. I have also tried to locally export the BytesIO into an actual file and send this file but no success. Maybe it's a browser problem?
Upvotes: 1
Views: 125
Reputation: 4269
since you want to send .xlsx
(Microsoft Excel OpenXML) and not .xls
(Microsoft Excel), i think you have to force the right mimetype
parameter in send_file()
like :
[..]
#finally return the file
return send_file(output,
attachment_filename="testing.xlsx",
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", # here
as_attachment=True)
refer to the https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Upvotes: 2