django admin
后台需要导出 excel
文件. 除了用插件, 也可以自己简单的实现.
lib
目录是一些自己写的库, 在 settings
文件里面把它加入了 sys.path
.
导出的时候需要选中要导出的数据才能导出, 不然只点导出按钮是无效的. 因为模型里面有些字段是 choice
所以增加判断, 有 get_xx_display
属性的时候, 返回比较友好的显示.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| from django.http import HttpResponse from openpyxl import Workbook
class ExportExcelMixin: ''' 通用导出 Excel 文件动作 '''
def export_as_excel(self, request, queryset): ''' 导出为 excel 文件. 文件名为 app名.模型类名.xlsx.
:param request: :param queryset: :return: ''' meta = self.model._meta field_names = [field.name for field in meta.fields] field_verbose_names = [field.verbose_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_verbose_names)
for obj in queryset: data = [] for field in field_names:
if hasattr(obj, f'get_{field}_display'): value = getattr(obj, f'get_{field}_display')() else: value = getattr(obj, field)
data.append(f'{value}')
ws.append(data)
wb.save(response)
return response
export_as_excel.short_description = '导出Excel'
|
1 2 3 4 5 6 7 8 9 10 11
| from django.contrib import admin
from export import ExportExcelMixin from .models import *
class XXAdmin(admin.ModelAdmin, ExportExcelMixin): ...
actions = ['export_as_excel']
|
参考链接