0

I have an issue with trying to serve my excel file as an httpresponse, it is coming out almost double in size and is corrupt when I try to open it.

My setups is as follows:

  1. I have an excel template which I make a copy of using shutil2
  2. I then open the copy using load_workbook() in openpyxl
  3. I populate the workbook with data

I then (as per the openpyxl docs) save the workbook as a stream and save it as an httpresponse object to be returned to my website through django

with NamedTemporaryFile() as tmp:
    wb.save(tmp.name)
    tmp.seek(0)
    stream = tmp.read()

response = HttpResponse(content=stream, content_type="application/ms-excel")
# I've also tried with application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
response['Content-Disposition'] = 'attachment; filename=Excel.xls'
return response

In my template I have some jquery code which downloads the excel for the user. This is done following the answer from this question: Get excel file (.xlsx) from server response in ajax

This all works fine, but the resulting download file is corrupt and while I am expecting it to be around 7mb in size, its actually 16mb.

Does anyone have any idea what I am doing wrong?

chaylins
  • 215
  • 1
  • 11

1 Answers1

0

Have you tried to open this in binary mode ? That helped me. I believe below code should help:

with NamedTemporaryFile(mode='rb') as tmp: ..

mvitor
  • 37
  • 8