Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return excel file from pandas with flask

Tags:

In flask I would like to return an excel file as output.

This code works well for csv:

    out = StringIO()
    notification_df.to_csv(out)
    resp = make_response(out.getvalue())
    resp.headers["Content-Disposition"] = "attachment; filename=output.csv"
    resp.headers["Content-type"] = "text/csv"
    return resp

I tried to adapt it so that it can output an excel file with various tabs (that originate from a pandas dataframe) but that doesn't work:

output = StringIO()
writer = ExcelWriter(output)
trades_df.to_excel(writer, 'Tab1')
snapshots_df.to_excel(writer, 'Tab2')
# writer.close() # causes TypeError: string argument expected, got 'bytes'

resp = make_response(output.getvalue)
resp.headers['Content-Disposition'] = 'attachment; filename=output.xlsx'
resp.headers["Content-type"] = "text/csv"
return resp

The problem is that I get an error TypeError: string argument expected, got 'bytes' when I do writer.close(). But when I leave it I get: Exception: Exception caught in workbook destructor. Explicit close() may be required for workbook.

Any solution are appreviated.

like image 602
Nickpick Avatar asked Oct 26 '16 17:10

Nickpick


1 Answers

For the ones who end up here, this should work:

from flask import Response
import io
buffer = io.BytesIO()

df = pd.read_excel('path_to_excel.xlsx', header=0)
df.to_excel(buffer)
headers = {
    'Content-Disposition': 'attachment; filename=output.xlsx',
    'Content-type': 'application/vnd.ms-excel'
}
return Response(buffer.getvalue(), mimetype='application/vnd.ms-excel', headers=headers)
like image 167
Manuel Montoya Avatar answered Sep 24 '22 16:09

Manuel Montoya