Last active
April 17, 2023 01:16
-
-
Save thomascenni/edcecdfda4d05dbe6aed6f27fc4d36a6 to your computer and use it in GitHub Desktop.
Return Excel file from Pandas Dataframe in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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