from django.shortcuts import reverse,redirect,render from operations import models import xlwt import os from io import BytesIO from django.http import HttpResponse def phone_download(request): phone_all = models.Phone.objects.all() if phone_all: # 创建工作簿 wb = xlwt.Workbook(encoding='utf-8') sheet = wb.add_sheet('order-sheet') # 写入文件标题 sheet.write(0, 0, '厂商') sheet.write(0, 1, '型号') sheet.write(0, 2, 'CPU') sheet.write(0, 3, '系统版本') data_row = 1 for i in phone_all: sheet.write(data_row, 0, i.firms) sheet.write(data_row, 1, i.model) sheet.write(data_row, 2, i.CPU) sheet.write(data_row, 3, i.version) data_row = data_row + 1 # 保存于本地 # exist_file = os.path.exists("test.xls") # if exist_file: # os.remove(r"test.xls") # wb.save("test.xls") # 返回文件给用户,用户操作浏览器对话框保存文件 sio = BytesIO() wb.save(sio) sio.seek(0) # http响应头告知浏览器,返回excel response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel') # 浏览器打开/保存的对话框 response['Content-Disposition'] = 'attachment; filename=test.xls' # 响应体 response.write(sio.getvalue()) return response
models数据结构
class Phone(models.Model): id = models.AutoField(primary_key=True) firms = models.CharField(max_length=32,verbose_name="厂商") model = models.CharField(max_length=32,verbose_name="型号") CPU = models.CharField(max_length=32,verbose_name="CPU") version = models.CharField(max_length=32,verbose_name="系统版本")