Django admin后台数据导出excel

admin后台加入excel导出数据功能,不修改前端代码,只更改后台代码。
1.admin.py文件内容

# -*- coding: utf-8 -*-
# @Time  : 2019/7/18 14:20
# @File  : admin.py
import xlwt as xlwt
from django.contrib import admin
from django.http import HttpResponse

from models import WLIndex


class WLIndexAdmin(admin.ModelAdmin):

    list_display = ('i_c_name', 'i_e_name')
    list_filter = ('i_c_name', 'i_e_name')
    search_fields = ('i_c_name', 'i_e_name')
    actions = ['export_excel']

    def export_excel(self, request, queryset):
        wb = xlwt.Workbook(encoding='utf-8')  # 开始创建excel
        LST_test = wb.add_sheet('值班日志异常汇总表', cell_overwrite_ok=True)  # excel中的表名
        wid1 = LST_test.col(0)
        wid1.width = 80 * 80
        wid2 = LST_test.col(1)
        wid2.width = 80 * 80
        wid3 = LST_test.col(2)
        wid3.width = 80 * 80
        wid4 = LST_test.col(3)
        wid4.width = 80 * 80
        wid5 = LST_test.col(4)
        wid5.width = 80 * 80
        LST_test.write(0, 0, '报错步骤', xlwt.easyxf('font: height 240, colour_index red,'))
        LST_test.write(0, 1, '报表时间', xlwt.easyxf('font: height 240, colour_index red,'))
        LST_test.write(0, 2, '报错原因', xlwt.easyxf('font: height 240, colour_index red,'))
        LST_test.write(0, 3, '解决方法', xlwt.easyxf('font: height 240, colour_index red,'))
        LST_test.write(0, 4, '报错处理人', xlwt.easyxf('font: height 240, colour_index red,'))
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment;filename=1.xlsx'
        wb.save(response)
        return response

    export_excel.short_description = '导出Excel'


admin.site.register(WLIndex, WLIndexAdmin)

2.界面效果:
Django admin后台数据导出excel_第1张图片
3.执行下载需要先选中你要下载的数据,执行效果:
Django admin后台数据导出excel_第2张图片

你可能感兴趣的:(Django,python)