Skip to content

Instantly share code, notes, and snippets.

@jonperron
Created November 15, 2016 13:03
Show Gist options
  • Save jonperron/4676abb810252151fc65663abbe6b6c3 to your computer and use it in GitHub Desktop.
Save jonperron/4676abb810252151fc65663abbe6b6c3 to your computer and use it in GitHub Desktop.
Sharing pandas dataframe as xlsx files without (too) much trouble. Using xlsxwriter from http://xlsxwriter.readthedocs.io/working_with_pandas.html
import numpy as np
import pandas as pd
import StringIO
def testExport(request):
# creating a dataframe and doing stuff about it
testDataframe = pd.DataFrame(np.random.randn(1,4), columns=list('ABCD'))
# generate output
output = StringIO.StringIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
testDataframe.to_excel(writer)
writer.save()
writer.close()
# now, sending the dataframe to the user
output.seek(0)
response = HttpResponse(output.read(),content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="testDataframe.xlsx"'
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment