2017-04-04 87 views
0

我希望能够将某些Django模型转换为Excel文件。我的看法如下:使用Django转换为Excel

@login_required 
def archive_to_excel(request): 
    calculations_list = Calculations.objects.filter(user=request.user) \ 
              .values_list('make', 'model', 'first_registration', 'body', 'facelift', 
                 'engine', 'transmission', 'purchase_price', 'mileage', 
                 'customer__firstname', 'customer__lastname', 'customer__email') \ 
              .order_by('-id') 

    columns = [_('Make'), _('Model'), _('First registration'), _('Body'), _('Facelift'), _('Engine'), _('Transmission'), 
       _('Price'), _('Mileage'), _('Customer first name'), _('Customer last name'), _('Customer email')] 

    return convert_to_excel("archive", columns, calculations_list) 

而且convert_to_excel功能如下:

def convert_to_excel(file_name, columns, values): 
    response = HttpResponse(content_type='application/ms-excel') 
    response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(file_name) 

    wb = xlwt.Workbook(encoding='utf-8') 
    ws = wb.add_sheet(file_name.capitalize()) 

    # Sheet header, first row 
    row_num = 0 

    font_style = xlwt.XFStyle() 
    font_style.font.bold = True 

    for col_num in range(len(columns)): 
     ws.write(row_num, col_num, columns[col_num], font_style) 

    # Sheet body, remaining rows 
    font_style = xlwt.XFStyle() 

    for row in values: 
     row_num += 1 
     for col_num in range(len(row)): 
      ws.write(row_num, col_num, row[col_num], font_style) 

    wb.save(response) 
    return response 

这工作正常,但我有问题是purchase_priceCalculations模型存储不含税我想在Excel文件INCL VAT中显示。

如何将purchase_price与1.21相乘,并将其显示在excel文件中?

有什么建议吗?

回答

1

例如你可以这样做:

calculations_list = Calculations.objects.filter(user=request.user) \ 
        .values_list('make', 'model', 'first_registration', 'body', 'facelift', 
           'engine', 'transmission', 'mileage', 
           'customer__firstname', 'customer__lastname', 'customer__email') \ 
        .annotate(purchase_price=F('purchase_price')*1.21) 
        .order_by('-id')