路由
path(r'^export/xls/$', views.export_excel, name='export_excel'),
函数
import xlwt
from django.http import HttpResponse
from django.contrib.auth.models import User
def export_excel(request):
"""导出记录的视图"""
device_li = Goods.objects.all() #查询库里所有数据
# 设置HTTPResponse的类型
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment;filename=device_data.xls'
"""导出excel表"""
if device_li:
# 创建工作簿
ws = xlwt.Workbook(encoding='utf-8')
# 添加第一页数据表
w = ws.add_sheet('sheet1') # 新建sheet(sheet的名称为"sheet1")
# 写入表头
w.write(0, 0, u'名称')
w.write(0, 1, u'价格')
w.write(0, 2, u'id')
# 写入数据
excel_row = 1
for obj in device_li:
name = obj.name
price = obj.price
id = obj.id
w.write(excel_row, 0, name)
w.write(excel_row, 1, price)
w.write(excel_row, 2, id)
excel_row += 1
# 写出到IO
output = io.BytesIO()
ws.save(output)
# 重新定位到开始
output.seek(0)
response.write(output.getvalue())
return response
视图
<h3><a href="{% url 'export_excel' %}">Export all goods</a></h3>