Django Admin中增長導出Excel功能

參考: https://www.cnblogs.com/yoyo008/p/9232805.htmlhtml

在使用Django Admin時, 對於列表咱們有時須要提供數據導出功能, 以下圖: 增長導出Excel功能django

在Django Admin中每一個模型的Admin類(繼承至admin.ModelAdmin), 咱們能夠經過actions增長支持的動做, 值爲當前類存在的方法名, 例如:app

.......
@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方法詳細實現以下:3d

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類使用, 完整代碼以下:excel

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']
相關文章
相關標籤/搜索