from datetime import datetime
from django.http import HttpResponse
from django.contrib.admin.templatetags import admin_list
from django.contrib.admin.utils import lookup_field
from django.utils.safestring import SafeString
from bs4 import BeautifulSoup
from openpyxl import Workbook
class ExportExcelMixin(object):
def get_export_ignore(self, request):
return []
def export_as_excel(self, request, queryset):
response = HttpResponse(content_type='application/msexcel')
download_filename = '{}_{}.xlsx'.format(self.model._meta, datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))
response['Content-Disposition'] = 'attachment; filename={}'.format(download_filename)
wb = Workbook()
ws = wb.active
cl = self.get_changelist_instance(request)
headers = admin_list.result_headers(cl)
ws.append([str(field['text']) for field in headers][1:])
for obj in queryset:
results = []
for display in self.get_list_display(request):
if display in self.get_export_ignore(request):
results.append(None)
continue
result = lookup_field(display, obj, cl.model_admin)[2]
if type(result) is SafeString:
result = BeautifulSoup(result, features="html.parser").text
results.append(str(result))
row = ws.append(results)
wb.save(response)
return response
export_as_excel.short_description = '导出Excel'
3.给指定Admin模型添加导出方法
1
2
3
4
5
6
7
8
9
10
from django.contrib import admin
from order.admin import ExportExcelMixin
from order.models import Order
# 例举订单模型
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin, ExportExcelMixin):
# other code
actions = ['export_as_excel']
# other code