1

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?

Arun Nair
  • 305
  • 2
  • 9
  • 2
    It probably isn't possible to "stream" a xlsx file since it is a zip file and it cannot be sent until the file is completely written. It isn't like a CSV file like in the link above. – jmcnamara Oct 29 '20 at 14:47
  • @jmcnamara is right, but the technical reason why it throws error is that StreamingHttpResponse first argument is supposed to be iterator. – Maddog Nov 05 '21 at 13:16

0 Answers0