2013-02-23 62 views
2

我正在導出數據庫字段爲Excel文件,一切工作正常,但我的外鍵字段被打印爲外鍵ID而不是實際值。Python XLWT外鍵值

我該如何解決?

這裏是我的代碼:

book = xlwt.Workbook(encoding='utf8') 
    sheet = book.add_sheet('Expense summary', cell_overwrite_ok=True) 
    header_style = xlwt.easyxf('font:height 280, color blue, bold 1; border: bottom thick;') 
    sum_style = xlwt.easyxf('font:height 200, color green, bold 1; border: top thick;') 
    date_style = xlwt.XFStyle() 
    date_style.num_format_str = 'DD-MM-YYYY' 
    currency_style = xlwt.XFStyle() 
    currency_style.num_format_str = '#,##0.00' 
    xls_values = expense.filter(
           user=request.user.id).values_list('date', 'amount', 'towho', 'forwhat', 'category', 'payment_method') 
    headers = (ugettext("Date"), ugettext("Amount"), ugettext("To who"), ugettext("For what"), ugettext("Category"), ugettext("Payment method")) 
    for i, header in enumerate(headers): 
     col_width = 256 * 20 
     sheet.col(i).width = col_width 
     sheet.row(0).write(i, header, header_style) 
    for row, rowdata in enumerate(xls_values): 
     for col, val in enumerate(rowdata): 
      if col == 0: 
       sheet.write(row + 1, col, val, date_style) 
      else: 
       if col == 1: 
        sheet.write(row + 1, col, val, currency_style) 
       else: 
        sheet.write(row + 1, col, val) 
    response = HttpResponse(mimetype='application/vnd.ms-excel') 
    response['Content-Disposition'] = 'attachment; filename=sample.xls' 
    book.save(response) 
    return response 

類別字段返回的ID號,而不是價值。

由於提前

+0

顯示你的代碼 - 你是如何導出到Excel?已經嘗試過了什麼? – 2013-02-23 07:59:43

回答

2

而不是列舉rowdata,通過現場生成行字段:

for row, o in enumerate(xls_values): 
    sheet.write(row + 1, 0, o.my_first_field, date_style) 
    sheet.write(row + 1, 1, o.my_second_field, val, currency_style) 
    sheet.write(row + 1, 2, o.my_category_field.name, val) # assuming name is what you want 
+0

工程就像一個魅力,謝謝。 – yaniv14 2013-02-23 18:17:47