【问题标题】:How to export information display in table to excel django如何将表格中的信息显示导出到excel django
【发布时间】:2019-09-19 11:44:49
【问题描述】:

我想将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模块docs.python.org/3/library/csv.html,它可以为您创建一个有效的CSV文件
  • 请只使用相关标签(固定)。
  • 看起来您已经有一些代码在做正确的事情(好吧,可能不是以最直接的方式,但是),那么您的问题是什么?注意:请不要回答“它不起作用” - 如果它“不起作用”,那么您必须确切地解释它是如何不起作用的(如果您有例外,请发布确切的异常消息和完整的回溯)。
  • 除了其他有用的功能外,您还可以使用django-tables2 轻松导出多种格式的数据。如果你对这个包感兴趣,我可以给你写一个 sn-p。
  • 目前,当我点击链接:export-data时,它只是刷新了页面,没有下载excel文件。所以我不确定它有什么问题,因为它不会提示任何错误。只是没有将表格的内容下载到 excel 表中@brunodesthuilliers

标签: python django


【解决方案1】:

您可以使用django-tables2。安装并添加到INSTALLED_APPS。您还需要为导出功能安装tablib。在您的应用文件夹下创建一个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 类和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结合使用。

【讨论】:

    【解决方案2】:

    首先report_line 字典引用了一个在方法范围内不存在的student 变量。根据您的问题here 我想您想导出模板中显示的数据。

    我还建议使用完整的代码集更新当前问题。

    为了实现这一点,您可以执行以下操作:

    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(r'^export/csv/$', views.file_load_view, name='export_data')
    

    在您的模板中:

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

    这用于将数据导出到csv 文件。查看您的文件扩展名,这似乎是您正在寻找的行为。如果您想导出到excel 文件,我建议您查看第三方库,例如xlwt

    【讨论】:

    • 嗨,Marcell,试图将我的代码更改为您的。管理相应地导出文件。但是,导出的数据不正确。就像在网站上一样:学生,安妮有 200 分,但导出时的值只有 100 分。我猜总和不能正常工作?我该如何解决这个问题?
    • 好的修复它。而不是“students = students.values_list('studName__VMSAcc', 'attendance')”,我应该将出勤率改为标记。感谢您的帮助!
    • 啊,是的,我会更新答案。如果这是正确的答案,请接受。
    • 确定! :) 无论如何,是否可以在我的 Views.py 下执行 if-else 语句。我想要做的是将标记转换为百分比。如果学生有 200 分,那么它将显示 100%,如果 100 分则显示 90% 左右。
    • 我看看这个答案stackoverflow.com/questions/19286834/…我想这就是你要找的。​​span>
    【解决方案3】:

    请参阅以下示例以 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 文档中有更多示例,请参见 link

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2023-03-16
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多