You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于给定Django模型代码生成客户信息Excel报表

基于Django模型生成客户Excel报表实现方案

首先安装依赖库openpyxl,执行命令:
pip install openpyxl


实现步骤

  • 关联三个模型的关联数据,三者均通过外键绑定customer表,可使用关联查询减少数据库请求次数
  • 自定义Excel表头、填充对应数据
  • 配置响应头,直接返回可下载的Excel文件
  • 可选调整:如需给单个客户对应多条联系信息/证件信息的场景,可自行扩展行展开逻辑

完整代码示例

视图函数代码(views.py)

from django.http import HttpResponse
from openpyxl import Workbook
from .models import customer, info, detail

def export_customer_excel(request):
    # 初始化Excel工作簿
    wb = Workbook()
    ws = wb.active
    ws.title = "客户数据报表"

    # 写入表头,可按需扩展字段
    headers = ["客户名称", "联系邮箱", "手机号码", "Aadhar证件存储路径"]
    ws.append(headers)

    # 关联查询所有客户数据
    customer_list = customer.objects.prefetch_related('info_set', 'detail_set').all()
    for cus in customer_list:
        # 读取关联的客户联系信息
        cus_info = cus.info_set.first()
        email = cus_info.email if cus_info else "无"
        phone = cus_info.phone_number if cus_info else "无"

        # 读取关联的客户证件信息
        cus_detail = cus.detail_set.first()
        aadhar_path = cus_detail.aadhar.path if (cus_detail and cus_detail.aadhar) else "无"

        # 写入单行数据
        ws.append([cus.name, email, phone, aadhar_path])

    # 配置下载响应
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    response['Content-Disposition'] = 'attachment; filename=customer_report.xlsx'
    wb.save(response)
    return response

路由配置代码(urls.py)

from django.urls import path
from . import views

urlpatterns = [
    # 原有路由保留,新增导出接口路由
    path('export/customer/', views.export_customer_excel, name='export_customer_excel'),
]

注意事项

  • 如果需要在Excel中插入证件图片而非仅存储路径,可以调用openpyxl的Image模块实现,需提前调整对应行的行高和列宽适配图片尺寸
  • 数据量超过1万条时建议替换为StreamingHttpResponse流式响应,避免服务器内存占用过高

内容的提问来源于stack exchange,提问作者vtr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:15:03