How to export information display in table to excel django

how to export data from python to excel
python script to export data to excel
export html table to excel django
django-import-export
django download excel file
how to export to excel
django-tables2 export example
python flask export to excel

I want to export the information display in the template under table tag to excel. I already tried to implement code but it is now exporting the information.

This is my template:

<div id="info" style="padding-left: 130px">
 <table class="table table-hover" style="width: 1200px;">
<thead>
     <tr><th> Student Name</th>
     <th> Attendance Mark </th>
     </tr>
</thead>
<tbody>
    {% for student in students %}
    <tr><td>{{student.studName__VMSAcc}}</td>
        <td>{{student.mark}}</td>
        </tr>   
    {% endfor %}
</tbody>
  </table>
  <a href="{% url 'exportdata' %}">export data</a>
  </div>

My View.py

 #to display the attended students in the table form
 def attStudName(request):

students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'))
if (mark): 
    ttlmark = (mark/200) *100
    context = {
    'students' : students,
    'ttlmark': ttlmark
    }
return render(request,'show-name.html',context)


#to extract the infomation displayed in the table.
def file_load_view(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="report.csv"'
    writer = csv.writer(response)
    writer.writerow(['Student Name', 'Attendance'])

    students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'))

    #convert the students query set to a values list as the writerow expects a list/tuple
    students = students.values_list('studName__VMSAcc', 'attendance')

    for student in students:
        writer.writerow(student)
    return response

My URLS.py

 url(r'^export/csv/$', views.file_load_view, name="export_data")

Above is my updated assisted by Marcell. Ive managed to export the required data. My question is: am I allowed to use if-else statement in my views.py? What i am trying to do is, to convert the mark to percentage. If students have 200 marks, then it will display 100%, if 100 marks then 90% or so.


First of all the report_line dictionary is referencing a student variable that does not exists in the scope of the method. Based on your question here I presume you want to export the data displayed in your template.

Also I would recommend updating current question with the complete code set.

In order to achieve that you can do something like this:

import csv

from django.http import HttpResponse

def file_load_view(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachement; filename="report.csv"'

    writer = csv.writer(response)
    writer.writerow(['Student Name', 'Attendance'])

    students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'))

    # Note: we convert the students query set to a values_list as the writerow expects a list/tuple       
    students = students.values_list('studName__VMSAcc', 'mark')

    for student in students:
        writer.writerow(student)

    return response

Your url will look something like this:

 url(r'^export/csv/$', views.file_load_view, name='export_data')

In your template:

<a href="{% url 'export_data' %}">Export Data</a>

This is for exporting data to csv file. Looking at your file name extension it seems this is the behaviour you are looking for. If you want to export to excel file I would recommend looking at a third party library like xlwt

How to download data as CSV and Excel file in Django, If you want to allow exporting the data present in your django-tables2 tables to various formats, you must install the csv, json, latex, ods, tsv, xls, xlsx, yaml. You can use the export_url template tag included with django_tables2 to render a link to export the data as csv: { % export_url "csv" % } This will make sure any other query string parameters will be preserved, for example in combination when filtering table items.


See the below example to export the data in csv format:

import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response

You can modifiy your code similar to above example. There are more example in offical django document see this link.

Exporting table data, csv file using Python's csv module; (2) export data to a .xls file using a third-party module named xlwt. For both cases, consider we are exporting  How to Export Data to XLSX Files A while ago I wrote an article about exporting data to different spreadsheet formats . As recently I was reimplementing export to Excel for the 1st things 1st project, I noticed that the API changed a little, so it's time to blog about that again.


You can use django-tables2. Install it and add it to INSTALLED_APPS. You'll also need to install tablib for the export feature. Create a tables.py file under your app folder:

import django_tables2 as tables
from .models import Student

class StudentTable(tables.Table):
    export_formats = ['xls', 'xlsx', 'csv']  # a list of formats you'll like to export to
    class Meta:
        model = Student
        fields = ('name', 'mark')
        # There are more Meta attributes you can use, just look for them in the docs.

Then use the SingleTableView class with ExportMixin in your views.py:

from django_tables2.views import SingleTableView
from django_tables2.export.views import ExportMixin
from .models import Student
from .tables import StudentTable

class StudentList(ExportMixin, SingleTableView):
    model = Student
    table_class = StudentTable
    export_name = 'students_assistance'
    template_name = 'students/student_list.html'

Finally your student_list.html template should look like this:

{% load django_tables2 %}
<div>
  {% for format in table.export_formats %}
    <a href="{% export_url format %}">.{{ format }}</a>
  {% endfor %}
</div>
{% render_table table %}

There's a lot more you can do with django-tables2, this is just a basic implementation. You can also combine it with django-filter.

How to Export to Excel, It's a simple model with title, description, and - of course - the id. # models.py from django.db import models class MyModel(models.Model): title =  In this article, the main subject was creating an Excel file in a Python/Django application. In a future article the attention will be drawn to PDF, another way to export data. * The Excel files from the screenshots were opened with LibreOffice. UPDATE: In this article, the main subject was creating an Excel file in a Python/Django application.


How to Export Your Data as CSV, XLS, or XLSX, This tutorial will show you how to export Excel files in Python/Django and how to application, many clients require pages which display statistics. Before adding any actual data to the file, we can create a table in the Excel,  Download data as Excel file in Django: For downloading data in excel file we need to add xlwt package in our environment. I assume you are using virtual environment to develop your django app.


How to export Excel files in a Python/Django application, import csv from django.http import HttpResponse def some_view(request): This short template iterates over the given data and displays a line of CSV for each  The button triggers exportTableToExcel () function to export HTML table data using JavaScript. < button onclick = "exportTableToExcel ('tblData')" >Export Table Data To Excel File</ button >. If you want to export data with the custom file name, pass your desired file name in the exportTableToExcel () function.


Outputting CSV with Django | Django documentation, Django tutorial, I will show you how to export a CSV file in Django. For more information Duration: 10:49 Posted: 30 Sep 2018 I will give you two options in this tutorial: (1) export data to a .csv file using Python’s csv module; (2) export data to a .xls file using a third-party module named xlwt. For both cases, consider we are exporting django.contrib.auth.models.User data.