Search code examples
djangoexceldjango-rest-frameworkopenpyxlexport-to-excel

How to properly append Django serialized data into excel sheet


I'm working on a task where I have to create an API URL that has some serialized data and I have to add it to the excel sheet.

I'm using openpyxl for this task.

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: List of 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 value inside fruit_serializer.data

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

data inside fruit is

Fruit Id
Fruit Name
Total Qty

fruit[data] value is

1
Apple
15
etc...

Output in Excel sheet is:

Excel Sheet Output

As you can see clearly the excel sheet output is not properly appended. I need to align them properly. I hope my question is clear.


Solution

  • I believe the block

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

    should be:

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