Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 605
jscriptor Avatar asked Jun 01 '19 13:06

jscriptor


People also ask

How do I download Pandas DataFrame in Excel?

Export a Pandas DataFrame Into Excel File by Using the to_excel() Function. When we export a pandas DataFrame to an excel sheet using the dataframe. to_excel() function, it writes an object into the excel sheet directly. To implement this method, create a DataFrame and then specify the name of the excel file.

How can I download Excel file in Django?

Download data as Excel file in Django: It is always recommended to user virtual environment. Once virtual environment is activated, Run this command to add xlwt package. Inside your view, import xlwt package. Use below code in your view in views.py file to create and download excel file.

How do I convert a panda to Excel?

Use pandas to_excel() function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.


1 Answers

As of pandas-0.17, 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).

like image 197
Willem Van Onsem Avatar answered Sep 29 '22 09:09

Willem Van Onsem