簡體   English   中英

如何將表格中顯示的信息導出到 excel django

[英]How to export information display in table to excel django

我想將table標簽下模板中顯示的信息導出到excel。 我已經嘗試實現代碼,但它現在正在導出信息。

這是我的模板:

<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>

我的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

我的URLS.py

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

以上是我在 Marcell 協助下的更新。 我設法導出了所需的數據。 我的問題是:我可以在views.py 中使用if-else 語句嗎? 我想要做的是將標記轉換為百分比。 如果學生有 200 分,那么它將顯示 100%,如果 100 分,則顯示 90% 左右。

請參閱以下示例以 csv 格式導出數據:

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

你可以修改你的代碼類似於上面的例子。 官方 django 文檔中有更多示例,請參見此鏈接

首先, report_line字典引用了該方法的 scope 中不存在的student變量。 根據您的問題我假設您要導出模板中顯示的數據。

此外,我建議使用完整的代碼集更新當前問題。

為了實現這一點,您可以執行以下操作:

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

您的 url 將如下所示:

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

在您的模板中:

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

這用於將數據導出到csv文件。 查看您的文件擴展名,這似乎是您正在尋找的行為。 如果您想導出到excel文件,我建議您查看第三方庫,例如xlwt

您可以使用django-tables2 安裝它並將其添加到INSTALLED_APPS 您還需要為導出功能安裝tablib 在你的 app 文件夾下創建一個tables.py文件:

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.

然后在您的views.py中使用SingleTableView class 和ExportMixin

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'

最后你的student_list.html模板應該是這樣的:

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

你可以用django-tables2做更多的事情,這只是一個基本的實現。 您也可以將它與django-filter結合使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM