[Answered ]-Read django data from model and write it using xlsxwriter

2๐Ÿ‘

โœ…

I got this answer to my own question, this is just other model I used:

def xlsx(request):
    # Create a workbook and add a worksheet.
    output = io.BytesIO()
    workbook = xlsxwriter.Workbook(output, {'in_memory': True})
    worksheet = workbook.add_worksheet('Reporte3a5')
    bold = workbook.add_format({'bold': True})
    # Some data we want to write to the worksheet.
    reporte = Reporte3a5.objects.all() #my model

    # Start from the first cell. Rows and columns are zero indexed.
    row = 1
    col = 0

    # Iterate over the data and write it out row by row.
    for linea in reporte:
        worksheet.write(row, col, linea.df_status)
        worksheet.write(row, col + 1, linea.aged)
        worksheet.write(row, col + 2, linea.ship_set)
        row += 1

    # Write the title for every column in bold
    worksheet.write('A1', 'Priority', bold)
    worksheet.write('B1', 'Code', bold)

    workbook.close()

    output.seek(0)
    response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = "attachment; filename=Reporte3a5.xlsx"

    return response

With this you will get the file automatically downloaded in the same page.

๐Ÿ‘คDeluq

Leave a comment