Excel de exportación de datos en segundo plano de administrador de Django

Agregue la función de exportación de datos de Excel en el backend de administración, no modifique el código de front-end, solo el código de back-end.
1. contenido del archivo 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. Efecto de interfaz:
Inserte la descripción de la imagen aquí
3. Para ejecutar la descarga, primero debe seleccionar los datos que desea descargar, el efecto de ejecución:
Inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/qq_42631707/article/details/105686438
Recomendado
Clasificación