Django 学习手册 - 下载数据库表格(XLS/CSV)

下载XLS表格方式:

前置:

  需要安装xlwt模块

views :

def export_users_xls(request):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="abc.xls"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Menu')
# Sheet header, first row row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True # 表头内容
columns = ['id','Mname'] for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle() # 获取数据库数据
rows = models.Menu.objects.all().values_list('id','Mname')
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response

URLS:(设置URLS)

 url(r'^export/xls/$', a1.export_users_xls, name='export_users_xls'),

前端页面:

 <a href="{% url 'export_users_xls' %}">Export all users</a>

下载CSV表格方式:

views :

import csv
from django.http import HttpResponse
from django.contrib.auth.models import User
def export_users_csv(request):
response = HttpResponse(content_type='text/csv')
# 表名
response['Content-Disposition'] = 'attachment; filename="users.csv"'
writer = csv.writer(response)
# 表头
writer.writerow(['Username', 'First name', 'Last name', 'Email address'])
# 表数据
users = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
for user in users:
writer.writerow(user)
return response

URLS:(设置URLS)

 url(r'^export/csv/$',a1.export_users_csv, name='export_users_csv'),

前端页面:

 <a href="{% url 'export_users_csv' %}">Export all users</a>
上一篇:一个bug


下一篇:2021-03-10