Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export data in python with excel format?

Tags:

python

django

views.py

def export_to_excel(request):

    lists = MyModel.objects.all()

    # your excel html format
    template_name = "sample_excel_format.html"

    response = render_to_response(template_name, {'lists': lists})

    # this is the output file
    filename = "model.csv"

    response['Content-Disposition'] = 'attachment; filename='+filename
    response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
    return response

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('app_name.views',
   url(r'^export/$', 'export_to_excel', name='export_to_excel'),  
)
  1. Last, in your page create a button or link that will point in exporting.

page.html

<a href="{% url app_name:export_to_excel %}">Export</a>

Nothing getting file option for download and not giving any error but i can see all result in log its working fine.

like image 321
Ashish Kumar Saxena Avatar asked Nov 18 '13 05:11

Ashish Kumar Saxena


2 Answers

I think that the solution to export excel files is :

   if 'excel' in request.POST:
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=Report.xlsx'
        xlsx_data = WriteToExcel(weather_period, town)
        response.write(xlsx_data)
        return response

In this example the library used for exporting is xlsxWriter. Here is a very complete and practical solution for this, and many others: http://assist-software.net/blog/how-export-excel-files-python-django-application .

like image 97
Alexandra Avatar answered Sep 30 '22 19:09

Alexandra


In addition to the options shown in the other answers you can also use XlsxWriter to create Excel files.

See this example.

like image 28
jmcnamara Avatar answered Sep 30 '22 19:09

jmcnamara