docx center text in table cells

minecraftplayer1234 picture minecraftplayer1234 · Mar 11, 2017 · Viewed 13.4k times · Source

So I am starting to use pythons docx library. Now, I create a table with multiple rows, and only 2 columns, it looks like this:

Now, I would like the text in those cells to be centered horizontally. How can I do this? I've searched through docx API documentation but I only saw information about aligning paragraphs.

Answer

user7609283 picture user7609283 · Mar 11, 2017

There is a code to do this by setting the alignment as you create cells.

doc=Document()
table = doc.add_table(rows=0, columns=2)
row=table.add_row().cells
p=row[0].add_paragraph('left justified text')
p.alignment=WD_ALIGN_PARAGRAPH.LEFT
p=row[1].add_paragraph('right justified text')
p.alignment=WD_ALIGN_PARAGRAPH.RIGHT

code by: bnlawrence

and to align text to the center just change:

p.alignment=WD_ALIGN_PARAGRAPH.CENTER

solution found here: Modify the alignment of cells in a table