在admin.py中新增动作Action
actions = [selected_download, ]
写自定义Action方法
from django.contrib import admin
from django.http import HttpResponse
from openpyxl import Workbook
@admin.action(description="导出Excel文件")
def selected_download(self, request, queryset):
records = list(queryset.values())
# 数据库的英文字段和中文字段的映射字典
zh_en = {
'昵称': 'nickname',
'产品': 'product',
'更新时间': 'updated',
'记录id': 'record_id'
}
zh = list(zh_en.keys())
# 转换数据格式,以方便openpyxl批量写入
records_list = [zh]
for r in records:
records_list.append([r[zh_en[k]] for k in zh])
# 开始批量写入数据
wb = Workbook()
ws = wb.active
for row in records_list:
ws.append(row)
response = HttpResponse(content_type='application/vnd.ms-excel')
# filename可自定义
response['Content-Disposition'] = f'attachment; filename="{datetime.date.today()}.xlsx"'
wb.save(response)
return response