设置django后台 导出excel表

本文介绍了一种在Django后台管理中添加功能,导出数据到Excel的方法。首先安装了xlwt和openpyxl库,然后在admin.py中定义了一个IndoAdmin类,添加了export_as_excel方法,该方法将模型数据转换为Excel格式并提供下载。通过这个功能,可以方便地从Django后台批量导出邮箱等信息。
摘要由CSDN通过智能技术生成

帮助公司写了一个爬虫,需要将获取的邮箱导出到本地,因为之前接触过xadmin,所以知道可以直接通过后台导出来

1. 安装xlwt 和 openpyxl

pip3 install xlwt
pip3 install openpyxl 

2.修改对应APP的 admin.py

from django.contrib import admin
from .models import Url, Country, KeyWords, Info
import xlwt
from openpyxl import Workbook
from django.http import HttpResponse


class IndoAdmin(admin.ModelAdmin):
    actions = ["export_as_excel"]
    list_per_page = 500

    def export_as_excel(self, request, queryset):
        # print("queryset", queryset)
        meta = self.model._meta  # 用于定义文件名, 格式为: app名.模型类名
        # print("meta", meta)
        field_names = [field.name for field in meta.fields]  # 模型所有字段名

        response = HttpResponse(content_type='application/msexcel')  # 定义响应内容类型
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'  # 定义响应数据格式
        wb = Workbook()  # 新建Workbook
        ws = wb.active  # 使用当前活动的Sheet表
        ws.append(field_names)  # 将模型字段名作为标题写入第一行
        for obj in queryset:  # 遍历选择的对象列表
            # print(obj)
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]  # 将模型属性值的文本格式组成列表

            ws.append(data)  # 写入模型属性值
        wb.save(response)  # 将数据存入响应内容
        return response

    export_as_excel.short_description = '导出Excel'  # 该动作在admin中的显示文字


admin.site.register(Url)
admin.site.register(Country)
admin.site.register(KeyWords)
admin.site.register(Info, IndoAdmin)

这里添加的主要是这个代码,代码写有注释,很详细

    def export_as_excel(self, request, queryset):
        # print("queryset", queryset)
        meta = self.model._meta  # 用于定义文件名, 格式为: app名.模型类名
        # print("meta", meta)
        field_names = [field.name for field in meta.fields]  # 模型所有字段名

        response = HttpResponse(content_type='application/msexcel')  # 定义响应内容类型
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'  # 定义响应数据格式
        wb = Workbook()  # 新建Workbook
        ws = wb.active  # 使用当前活动的Sheet表
        ws.append(field_names)  # 将模型字段名作为标题写入第一行
        for obj in queryset:  # 遍历选择的对象列表
            # print(obj)
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]  # 将模型属性值的文本格式组成列表

            ws.append(data)  # 写入模型属性值
        wb.save(response)  # 将数据存入响应内容
        return response

    export_as_excel.short_description = '导出Excel'  # 该动作在admin中的显示文字
参考链接

【django】 django后台管理 导出excel表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cll_869241891

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值