django导出excel

# coding:utf-8
from django.http import HttpResponse
from xlwt import *
import StringIO, os
from test_celery.models import PhoneNumber

def excel_out(request):
    number_list = PhoneNumber.objects.all().order_by('time')
    if number_list:
        ws = Workbook(encoding='utf-8')
        w = ws.add_sheet(u'电话本', cell_overwrite_ok=True)
        w.write(0, 0, u'编号')
        w.write(0, 1, u'姓名')
        w.write(0, 2, u'性别')
        w.write(0, 3, u'时间')
        excel_row = 1
        for number in number_list:
            id = number.id
            name = number.name
            sex = number.sex
            time = str(number.time)
            w.write(excel_row, 0, id)
            w.write(excel_row, 1, name)
            w.write(excel_row, 2, sex)
            w.write(excel_row, 3, time)
            excel_row += 1

        # 保存于本地
        # exist_file = os.path.exists('phone.xls')
        # if exist_file:
        #     os.remove(r'phone.xls')
        # ws.save('phone.xls')

        # 返回文件给用户,用户操作浏览器对话框保存文件
        sio = StringIO.StringIO()
        ws.save(sio)
        sio.seek(0)
        # http响应头告知浏览器,返回excel
        response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
        # 浏览器打开/保存的对话框
        response['Content-Disposition'] = 'attachment;filename=phone.xls'
        # 响应体
        response.write(sio.getvalue())
        return response
上一篇:java中的锁池和等待池


下一篇:HDUOJ-----4510 小Q系列故事——为什么时光不能倒流