Skip to content

Instantly share code, notes, and snippets.

@thomascenni
Last active April 17, 2023 01:16
Show Gist options
  • Save thomascenni/edcecdfda4d05dbe6aed6f27fc4d36a6 to your computer and use it in GitHub Desktop.
Save thomascenni/edcecdfda4d05dbe6aed6f27fc4d36a6 to your computer and use it in GitHub Desktop.
Return Excel file from Pandas Dataframe in Django
import pandas as pd
from io import BytesIO
from django.http import HttpResponse
# suppose to have a Dataframe object
# inside a Django view
df = pd.DataFrame(...)
with BytesIO() as b:
# Use the StringIO object as the filehandle.
writer = pd.ExcelWriter(b, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
filename = 'test'
content_type = 'application/vnd.ms-excel'
response = HttpResponse(b.getvalue(), content_type=content_type)
response['Content-Disposition'] = 'attachment; filename="' + filename + '.xlsx"'
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment