from django.http import HttpResponse
from xlwt import *
from io import StringIO, BytesIO
import os

@list_route()
def excel_export(self, request):
    \"\"\"
        导出excel表格
        \"\"\"
    list_obj = StudentInfo. s.all().order_by(\'-modified_time\')
    if list_obj:
        # 创建工作薄
        ws = Workbook(encoding=\'utf-8\')
        w = ws.add_sheet(u\"Sheet1\")
        w.write(0, 0, \"id\")
        w.write(0, 1, u\"学生姓名\")
        w.write(0, 2, u\"当前学校\")
        w.write(0, 3, u\"专业\")
        w.write(0, 4, u\"个人邮箱\")
        w.write(0, 5, u\"微信号\")
        w.write(0, 6, u\"联系手机\")
        # 写入数据
        excel_row = 1
        for obj in list_obj:
            data_id = obj.id
            data_name = obj.name
            # data_time = obj.time.strftime(\"%Y-%m-%d\")[:10]
            data_cschool = obj.cschool
            dada_major = obj.major
            dada_email = obj.email
            dada_wechat = obj.wechat
            dada_phone = obj.phone
            w.write(excel_row, 0, data_id)
            w.write(excel_row, 1, data_name)
            w.write(excel_row, 2, data_cschool)
            w.write(excel_row, 3, dada_major)
            w.write(excel_row, 4, dada_email)
            w.write(excel_row, 5, dada_wechat)
            w.write(excel_row, 6, dada_phone)
            excel_row += 1
        # 检测文件是够存在
        # 方框中代码是保存本地文件使用,如不需要请删除该代码
        ###########################
        # exist_file = os.path.exists(\"test.xls\")
        # if exist_file:
        #     os.remove(r\"test.xls\")
        # ws.save(\"test.xls\")
        ############################
        sio = BytesIO()  # 二进制和str的区分
        ws.save(sio)
        sio.seek(0)
        response = HttpResponse(sio.getvalue(), content_type=\'application/vnd.ms-excel\')
        response[\'Content-Disposition\'] = \'attachment; filename=data.xls\'
        response.write(sio.getvalue())
        return response

StringIO模块主要用于在内存缓冲区中读写数据
也可以直接存储在系统内存中,然后response url

收藏 打印