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.界面效果:
在这里插入图片描述
3.执行下载需要先选中你要下载的数据,执行效果:
在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值