[Django]-Exporting Django models to Excel (different sheets) using Django-tables2

2๐Ÿ‘

So, I came with a simple solution, probably not the most efficient, by using pandas. Convert the queryset to pandas dataframe and use pandas ExcelWriter to generate the excel and it can be done for different sheets. Probably for deployment with large data, might be better to use libraries like xlsxwriter but it works for what I wanted to do.

    iden= request.GET["id"]
    output = BytesIO()
    queryset = Efectivo.objects.filter(Q(id1=iden)).values()
    df = pd.DataFrame(queryset)
    writer = pd.ExcelWriter(output,engine='xlsxwriter')
    df.to_excel(writer,sheet_name='Efectivo')
    writer.save()
    output_name = 'example'
    output.seek(0)
    response = HttpResponse(output, 
    content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename={output_name}.xlsx'
        
    
    return response```
๐Ÿ‘คquechua685

0๐Ÿ‘

Try using xlsxwriter:

response = HttpResponse(content_type='application/vnd.ms-excel')
# tell the browser what the file is named
response['Content-Disposition'] = 'attachment;filename="file_name.xlsx"'
writer = pd.ExcelWriter(response, engine = 'xlsxwriter')
#d1 and d2 are pandas dataframe 
d1.to_excel(writer, sheet_name='Sheet1',index=False)
d2.to_excel(writer, sheet_name='Sheet2',index=False)
writer.save()
๐Ÿ‘คKing Katak

Leave a comment