django后台批量数据导出xls

app/admin.py

import xlwt
from django.shortcuts import HttpResponse
from django.contrib import admin
from io import BytesIO
from .models import *
      #实现数据导出的方法
    def export_data(self,request,queryset):
        xls_io = BytesIO()
        wb = xlwt.Workbook()
        ws = wb.add_sheet('export')
        count = 0
        #queryset 对应admin页面勾选的每一行数据类型为queryset
        for qs in queryset:
            row = [qs.id,qs.job,qs.title,qs.payment,qs.person.name]
            print(row)
            for index,value in enumerate(row):
                #行,列,值
                ws.write(count,index,value)
            count += 1
        wb.save(xls_io)
        res = HttpResponse()
        res["Content-Type"] = "application/octet-stream"
        res["Content-Disposition"] = 'filename="userinfos.xlsx"'
        res.write(xls_io.getvalue())
        self.message_user(request,'导出成功!')
        return res
    #注册这个方法
    actions = [export_data]
    #批量操作下拉菜单中显示方法描述信息
    export_data.short_description = '数据批量导出'

你可能感兴趣的:(django后台批量数据导出xls)