如何在python docx中垂直编写表

问题描述 投票:0回答:1

我正在将数据导出到Word Docx,得到这样的结果

enter image description here

使用此代码

records = Model.objects.filter(pk=pk)

table = document.add_table(rows=1, cols=3)

hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'data1'
hdr_cells[1].text = 'data2'
hdr_cells[2].text = 'data3'

for record in records:
    row_cells = table.add_row().cells
    row_cells[0].text = record.data1
    row_cells[1].text = record.data2
    row_cells[2].text = record.data3

但是我想要这样的东西

enter image description here

我已经尝试了多种方法,但是每次遇到错误时,如果我添加hdr_cells[3],我可能会有3个以上的数据,它将引发index out of range错误。请问有人可以帮忙吗?预先感谢!

python python-docx
1个回答
0
投票

一种方法是提取函数。您还需要根据查询结果形成表格的尺寸:

def write_column(col, record):
    cells = column.cells
    for i, field in record:
        cells[i].text = field

records = Model.objects.filter(pk=pk)
table = document.add_table(rows=len(records[0]), cols=len(records))
for i, record in enumerate(records):
    write_column(table.columns[i], record)

您尚未指定record对象的类型,因此我在这里假定了列表。您可能需要根据具体情况进行一些调整。

如果记录字段仅按属性名称可用(例如.data1.data2等),则需要包含或获取架构信息以进行映射,这可能会影响此代码对架构的灵活性更改(例如用于多种记录类型)。

© www.soinside.com 2019 - 2024. All rights reserved.