saving and dwnloading excel file in django
import pandas as pd
import os
import openpyxl
import xlwt
def Category1_excel(request):
    #saving file 
    category1=Download.objects.all()
    file=[]
    for i in category1:
        p=i.column1
        s=i.column2
        q=i.column3
        row=[p,s,q,e,l]
        file.append(row)
    document = pd.DataFrame(file)
    document.to_excel('media/file_downloads/category1.xlsx')
        #downloading file
    category1=Download.objects.all()    
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="file.xls"'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet("sheet1")
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    row_num = 0
    ws.write(row_num, 0,'PURCHASED GOODS', font_style)
    ws.write(row_num, 1, 'SUPPLIER', font_style)
    ws.write(row_num, 2, 'QUANTITY PURCHASED', font_style)
    ws.write(row_num, 3, 'SUPPLIER EMISSION', font_style)
    ws.write(row_num, 4, 'LOCATION', font_style)
    for my_row in category1:
        row_num = row_num + 1
        ws.write(row_num, 0, my_row.Purchased_good, font_style)
        ws.write(row_num, 1, my_row.Supplier, font_style)
        ws.write(row_num, 2, my_row.Quantity_purchased, font_style)
        ws.write(row_num, 3, my_row.Supplier_emision, font_style)
        ws.write(row_num, 4, my_row.Location, font_style)
    wb.save(response)
    return response
Comments
Post a Comment