如何正确地将 Django 序列化数据附加到 excel sheet

How to properly append Django serialized data into excel sheet

我正在执行一项任务,我必须创建一个 API URL,其中包含一些序列化数据,我必须将其添加到 excel sheet.

我正在使用 openpyxl 来完成这项任务。

def fruit_report_export(request):
    temp_file = "report.xlsx"

    media_doc_path = os.path.join(settings.MEDIA_ROOT, Reports
    if os.path.exists(media_doc_path):
        pass
    else:
        os.mkdir(media_doc_path)

    path = os.path.join(settings.MEDIA_ROOT, f"Reports/July-2021")
    if os.path.exists(path):
        excel_path = os.path.join(path, temp_file)
    else:
        os.mkdir(path)
        excel_path = os.path.join(path, temp_file)

    # creating excel
    wb = Workbook(excel_path)
    wb.save(excel_path)

    # add data into excel
    wb = load_workbook(filename=excel_path)
    wb_sheet = wb["Sheet"]
    wb_sheet.title = "Report"
    ws = wb["Report"]
    headers = ["Fruit Id", "Fruit Name", "Total Qty"]
    ws.append(headers)
    
    fruit_serializer = FruitSerializer(fruits, many=True)

    # looping through serializer data
    for fruit in fruit_serializer.data:
        for data in fruit
            ws.append([fruit[data] for h in headers])
    wb.save(excel_path)

    # Saving virtual workbook
    bytes = save_virtual_workbook(wb)
    response = HttpResponse(bytes, content_type="application/ms-excel")
    response["Content-Disposition"] = "attachment; filename=temp.xlsx"

    return response

fruit_serializer.data: OrderedDict列表

[
     OrderedDict([('Fruit Id', 1), ('Fruit Name', 'Apple'), ('Total Qty', 15)]),
     OrderedDict([('Fruit Id', 2), ('Fruit Name', 'Banana'), ('Total Qty', 25)]),
     OrderedDict([('Fruit Id', 3), ('Fruit Name', 'Mango'), ('Total Qty', 10)])
]

里面的水果值fruit_serializer.data

OrderedDict([('Fruit Id', 1), ('Fruit Name', 'Apple'), ('Total Qty', 25)])

水果里面的数据是

Fruit Id
Fruit Name
Total Qty

水果[数据]值为

1
Apple
15
etc...

Excelsheet中的输出是:

如您所见,excel sheet 输出未正确附加。我需要正确对齐它们。我希望我的问题很清楚。

我相信块

    for fruit in fruit_serializer.data:
        for data in fruit
            ws.append([fruit[data] for h in headers])

应该是:

    for fruit in fruit_serializer.data:
        ws.append([fruit[h] for h in headers])