Search code examples
pythonpython-docx

How to write table vertically in python docx


I am exporting data to Word Docx I am getting a result like this

enter image description here

with this code

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

but I am want to have it like this

enter image description here

I have tried a number of ways but every time I am getting an error and I might have more than 3 data if I add hdr_cells[3] it throws the index out of range error. please can anyone help on this issue? Thanks in advance!


Solution

  • One way is to extract a function. You'll also need to form the dimensions of the table from the query result:

    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)
    

    You haven't specified the type of the record object, so I've assumed list here. You might need some adjustments depending on the specifics.

    If record fields are only available by attribute name (like .data1, .data2, etc.), you'll need to include or get schema information to make that mapping, which could affect how flexible this code is to schema changes (like being used for more than one record type).