【发布时间】: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