pythonpython-3.xdjangoexceldownload

django pandas dataframe download as excel file


I have a Django app that will be placed in a Docker container.

The app prepares data in Dataframe format. I would like to allow the user to download the data to his/her local drive as excel file.

I have used df.to_excel in the past, but this won't work in this case.

Please advise best way to do this.


Solution

  • As of , you can let Django write to a BytesIO directly, like:

    from django.http import HttpResponse
    from io import BytesIO
    
    def some_view(request):
        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()
            # Set up the Http response.
            filename = 'django_simple.xlsx'
            response = HttpResponse(
                b.getvalue(),
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
            response['Content-Disposition'] = 'attachment; filename=%s' % filename
            return response

    You might need to install an Excel writer module (like xlsxwriter, or openpyxl).