简体   繁体   中英

How do I position tables in python docx?

I want to position two tables using python-docx. Naturally, I searched for answers online and nothing come close to what I want to achieve. What I want to do is place the two table side by side on the docx page. For example, if I have two table named tableA and tableB and I want to place tableA at the right and tableB at the right. Initially I tried aligning but it did not work. Below is my code.

from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
document = Document()
tableA = document.add_table(3,3)
tableB = document.add_table(3,3)
tableA.alignment = WD_TABLE_ALIGNMENT.LEFT
tableB.alignment = WD_TABLE_ALIGNMENT.RIGHT
document.save('test.docx')

Most folks would probably use a "container" table for this job, just a table with one row and two columns. Put the one table in the first cell and the other in the second cell. Try it out by hand using Word to get the gist.

A table cell is a block-item container, like a document is. That means it can contain paragraphs but also tables, both of which are block-items.

In python-docx it would look something like this:

container_table = document.add_table(1,2)
tableA = container_table.rows[0].cells[0].add_table(3, 3)
tableB = container_table.rows[0].cells[1].add_table(3, 3)

Another alternative would be to use a two-column layout, but that would be more complicated and I'm not sure what the advantage would be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM