Django Admin中增加导出Excel功能

2019-08-07  本文已影响0人  韩志超

参考: https://www.cnblogs.com/yoyo008/p/9232805.html

在使用Django Admin时, 对于列表我们有时需要提供数据导出功能, 如下图:


增加导出Excel功能

在Django Admin中每个模型的Admin类(继承至admin.ModelAdmin), 我们可以通过actions增加支持的动作, 值为当前类存在的方法名, 例如:

.......
@admin.register(Issue)
class IssueAdmin(admin.ModelAdmin):
    ......
    actions = ['export_as_excel']  # 增加动作, 对应相应的方法名
    def export_as_csv(self, request, queryset):  # 具体的导出csv方法的实现
        pass
    
    export_as_excel.short_description = '导出Excel'  # 该动作在admin中的显示文字

导出Excel方法详细实现如下:

from openpyxl import Workbook
....
    def export_as_excel(self, request, queryset):
        meta = self.model._meta  # 用于定义文件名, 格式为: app名.模型类名
        field_names = [field.name for field in meta.fields]  # 模型所有字段名

        response = HttpResponse(content_type='application/msexcel')  # 定义响应内容类型
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'  # 定义响应数据格式
        wb = Workbook()  # 新建Workbook
        ws = wb.active  # 使用当前活动的Sheet表
        ws.append(field_names)  # 将模型字段名作为标题写入第一行
        for obj in queryset:  # 遍历选择的对象列表
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]  # 将模型属性值的文本格式组成列表
            row = ws.append(data)  # 写入模型属性值
        wb.save(response)  # 将数据存入响应内容
        return response

由于导出Excel动作可以作为各个模型的通用动作, 我们可以封装成一个Mixin类使用, 完整代码如下:

from openpyxl import Workbook
from django.contrib import admin
from django.http import HttpResponse
from .models import  Issue

class ExportExcelMixin(object):
    def export_as_excel(self, request, queryset):
        meta = self.model._meta
        field_names = [field.name for field in meta.fields]

        response = HttpResponse(content_type='application/msexcel')
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'
        wb = Workbook()
        ws = wb.active
        ws.append(field_names)
        for obj in queryset:
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]
            row = ws.append(data)

        wb.save(response)
        return response

    export_as_excel.short_description = '导出Excel'

@admin.register(Issue)
class IssueAdmin(admin.ModelAdmin, ExportCsvMixin):
    fields = ('key', 'summary', 'status', 'project',
              'origin', 'components', 'prj_level', 'prj_category',
              'assignee', 'origin_person', 'pm', 'dev_manager', 'test_manager', 'tester', 'fe_dev', 'backend_dev',
              'plan_begin', 'plan_end', 'fe_plan_begin', 'fe_plan_end', 'test_plan_begin',
              'test_plan_end', 'backend_plan_begin', 'backend_plan_end',
              'created', 'reopen', 'prd_begin', 'prd_end', 'dev_begin', 'dev_end',
              'test_begin', 'test_end', 'pm_check', 'ready', 'pause', 'done',
              'pm_take', 'dev_take', 'test_take', 'total_take',
              'tags',
              )
    readonly_fields = fields
    list_display = ('key', 'summary', 'status', 'origin', 'components', 'created', 'visit')
    list_filter = ('origin', 'components', 'status', 'tags')
    search_fields = ('key', 'summary')
    date_hierarchy = 'created'
    actions = ['export_as_excel']
上一篇下一篇

猜你喜欢

热点阅读