Set django background to export excel table

Helped the company to write a crawler, which needs to export the obtained mailbox to the local, because I have been in touch with xadmin before, so I know that it can be exported directly through the background

1. Install xlwt and openpyxl

pip3 install xlwt
pip3 install openpyxl 

2. Modify the admin.py of the corresponding APP

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)

The main thing added here is this code, the code is written with comments, very detailed

    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中的显示文字

reference link

[django] django background management export excel table

Guess you like

Origin blog.csdn.net/cll_869241/article/details/118048911