加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

【django】 django后台管理 导出excel表

发布时间:2020-12-15 17:08:52 所属栏目:大数据 来源:网络整理
导读:from django.contrib import admin # Register your models here. xlwt from django.http HttpResponse from dal models Register your models here. from openpyxl Workbook class FundAdmin(admin.ModelAdmin): actions = [ " export_as_excel " ] list_di
from django.contrib import admin

# Register your models here.
 xlwt
from django.http  HttpResponse

from dal  models
 Register your models here.

from openpyxl  Workbook


class FundAdmin(admin.ModelAdmin):
    actions = ["export_as_excel"]
    list_display = ('title',nametypeunitstatuscreate_time')
    list_filter = [,]


    def export_as_excel(self,request,queryset):
        print(queryset 用于定义文件名,格式为: app名.模型类名
        metafor field in meta.fields]   模型所有字段名

        response = HttpResponse(content_type=application/msexcel')   定义响应内容类型
        response[Content-Disposition'] = fattachment; filename={meta}.xlsx'   定义响应数据格式
        wb = Workbook()   新建Workbook
        ws = wb.active   使用当前活动的Sheet表
        ws.append(field_names)   将模型字段名作为标题写入第一行
        for obj in queryset:   遍历选择的对象列表
            print(obj)
            in field_names:

                data = [f{getattr(obj,field)}' in field_names]   将模型属性值的文本格式组成列表

            ws.append(data)   写入模型属性值
        wb.save(response)   将数据存入响应内容
        return response


    export_as_excel.short_description = 导出Excel 该动作在admin中的显示文字



admin.site.register(models.Fund,FundAdmin)

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读