Django 2.2.5 | Python 3.6.12
I'm trying to create an xlsx file for download using a list of dictionaries through pandas. Since the file can become huge, I'm using StreamingHttpResponse() instead of normal HttpResponse(). The code that I have currently downloads the file but shows file format is invalid when I try and open it. I have referred to these two links as of now:
https://docs.djangoproject.com/en/3.1/howto/outputting-csv/#streaming-large-csv-files
Django Pandas to http response (download file)
Here's the code that I am using currently:
# 'emails' is the list of dictionaries
# 'list_name' contains the name of file
with BytesIO() as bio:
writer = pd.ExcelWriter(bio, engine='xlsxwriter')
dataframe = pd.DataFrame(data=emails)
dataframe.to_excel(writer, sheet_name="Verify Results")
writer.save()
bio.seek(0)
workbook = bio.getvalue()
response = StreamingHttpResponse(
workbook,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
response['Content-Disposition'] = f"attachment; filename={list_name}.xlsx"
return response
However, if I use
response = HttpResponse(
bio,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
it downloads and opens up correctly.
How do I use StreamingHttpResponse with pandas so that it downloads correctly?