最近在弄xadmin,希望做一个数据显示查询的页面。老板的要求是选择性的导出所选的信息。xadmin原本带有的导出功能是筛选完后的全部表格导出,无法实现个性化选择导出的功能。查阅了相关资料,在action功能中可以实现批量导出,最后实现了功能。
app下新建一个py文件放定义的action:
from django.http import HttpResponse
from xadmin.plugins.actions import BaseActionView
from xlwt import *
import os
from io import BytesIO
class MyAction(BaseActionView):
action_name = 'export_excel' # 随便起个名字
description = u'批量导出' # 页面中显示的操作名字
model_perm = 'view' #执行action需要的权限,其他的还有change,delete,add
def do_action(self, queryset):
ws = Workbook(encoding='utf-8')
w = ws.add_sheet(u"数据报表")
w.write(0, 0, "id")
excel_row = 1
for obj in queryset:
data_id = obj.id
w.write(excel_row,0,data_id)
excel_row += 1
exist_file = os.path.exists('data.xls')
if exist_file:
os.remove(r'data.xls')
ws.save('data.xls')
sio = BytesIO()
ws.save(sio)
sio.seek(0)
response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=data.xls'
response.write(sio.getvalue())
return response
from:https://blog.csdn.net/qq_18863573/article/details/51722907