Python XLWT 外键值

标签 python django excel foreign-key-relationship xlwt

我正在将数据库字段导出到 Excel 文件,一切正常,但我的外键字段被打印为外键 ID,而不是实际值。

如何修复它?

这是我的代码:

    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 号而不是值。

提前致谢

最佳答案

不是枚举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

关于Python XLWT 外键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15038153/

相关文章:

python - 如何在资源中搜索嵌套值(tastypie json)

vba - Excel VBA 运行时错误 13 - 框为空时不匹配

mysql - 通过在线 Excel 连接到 MySQL 数据库

python - 将数据从 pyspark 写入 azure blob?

Python 日期时间 : use strftime() with a timezone-aware date

python - 如何解释ntlk包中的 "most informative features"

java - 如何将外部excel文件的输入数据获取到cucumber(JAVA)中的特征文件中...?

python - Django: 'User' 对象不支持索引

python - 安装 django-templated-email

html - xhtml2pdf 不显示表格边框