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

在Django中导出Excel时如何将JSON格式商品数据格式化展示为列表

Django导出Excel时JSON字段格式化解决方案

修改思路

  • 引入json模块解析存储商品信息的JSON字符串
  • 为单元格样式开启自动换行属性,支持多行内容正常展示
  • 调整商品列宽度,避免内容被截断
  • 将解析后的商品信息拼接为结构化的多行文本再写入单元格

完整修改后代码

import json
import xlwt
from datetime import datetime
from django.http import HttpResponse
from .models import Booking

def export_packing_xls(request):
    response = HttpResponse(content_type='application/ms-excel')
    file_name = "packing_list_"+str(datetime.now().date())+".xls"
    response['Content-Disposition'] = 'attachment; filename="'+ file_name +'"'
 
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Packing List')

    date1 = request.GET.get('exportStartDate')
    date2 = request.GET.get('exportEndDate')
 
    # 表头配置
    row_num = 0
    header_style = xlwt.XFStyle()
    header_style.font.bold = True
 
    columns = ['Ref Number', 'Description of Goods','Gross WT',]
    # 如果需要保留QTY列,可在上方columns新增对应项,同时在下方values_list中补充查询的字段
    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], header_style)
 
    # 表格内容样式配置
    body_style = xlwt.XFStyle()
    # 开启自动换行
    body_style.alignment = xlwt.Alignment()
    body_style.alignment.wrap = 1
    # 调整商品列宽度为60个字符宽度
    ws.col(1).width = 256 * 60
 
    rows = Booking.objects.filter(created_at__range =[date1, date2]).values_list('booking_reference', 'product_list', 'gross_weight',)
    for row in rows:
        row_num += 1
        ref, product_json, gross_wt = row
        # 解析商品JSON
        try:
            product_list = json.loads(product_json)
            product_desc = ""
            for idx, item in enumerate(product_list, 1):
                # 可根据需要调整拼接展示的字段
                product_desc += f"{idx}. {item['Name']} 数量:{item['Quantity']} 单重:{item['Weight']}{item['WeightTypes']} 总重:{item['TotalWeight']}{item['WeightTypes']}\n"
            # 去除末尾多余换行
            product_desc = product_desc.rstrip('\n')
        except Exception:
            # 解析失败时保留原始内容
            product_desc = product_json
        
        # 逐列写入数据
        ws.write(row_num, 0, ref, body_style)
        ws.write(row_num, 1, product_desc, body_style)
        ws.write(row_num, 2, gross_wt, body_style)

    wb.save(response)
    return response

效果说明

修改后Description of Goods列的内容会按结构化展示,单个单元格内每行对应一个商品,示例如下:

  1. Fan 数量:12 单重:12KG 总重:144KG
  2. T shirt 数量:22 单重:5KG 总重:110KG

如果需要调整展示的商品字段,直接修改product_desc拼接逻辑即可。

内容的提问来源于stack exchange,提问作者Md Azharul Islam Somon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:45:09