实现方法
from django.contrib import admin
from datebase.models import *
from openpyxl import Workbook
from django.http import HttpResponse
# Register your models here.
# 导出Excel
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'
# 管理模块配置
class ExportAdmin(admin.ModelAdmin, ExportExcelMixin):
actions = ['export_as_excel']
def get_list_display(self, request):
lists=[]
for f in self.model._meta.fields:
lists.append(f.name)
return lists
# 注册管理模块
admin.site.register(Student, ExportAdmin)
实现效果
可以勾选数据进行导出
导出的文件内容