I'm working with Python 3. Here is the part that sets up the response for file download -
import io
import pandas as pd
@app.route('/download_log',methods=['GET'])
def download_log():
output = io.BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
# s is a Pandas Dataframe that I want to have downloaded as an excel
s.to_excel(writer, sheet_name='Sheet1')
writer.save()
output.seek(0)
excelDownload=output.read()
return send_file(excelDownload,attachment_filename='log.xlsx',as_attachment=True)
My main goal is that I need to make the contents of the dataframe(in this case 's') available as an xlsx download to the client and I do not want to save this file on the server (I have tried it and it works); I want to be able to do this on the fly. For this pandas only allows me to use io.BytesIO as input to ExcelWriter. The value in the DataFrame are actual strings but when I print excelDownload I get values of the form(This is just the first line)
b'PK\x03\x04\x14\x00\x00\x00\x08\x00\xf5c9J,)\xbdS\x13\x01\x00\x00\xc6\x01\x00\x
I am not sure if this is the source of my problems, but the xlsx gets downloaded at the client can't be opened; I get the error 'File can't be opened because file format or file extension may be invalid'. Do I need to decode the Byte stream before sending it as a response; if I do, which codec do I use? utf-8, latin-1 etc don't seem to be working. Also, I get the error - " Debugging middleware caught exception in streamed response at a point where response headers were already sent " in my console. I guess its because of the format of file I'm sending(excelDownload) How do I get all the details of the dataframe properly reproduced in the downloaded excel? I've spent a dozen hours on this and would be extremely grateful for any pointers