'docx center text in table cells

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.



Solution 1:[1]

The most reliable way that I have found for setting he alignment of a table cell (or really any text property) is through styles. Define a style for center-aligned text in your document stub, either programatically or through the Word UI. Then it just becomes a matter of applying the style to your text.

If you create the cell by setting its text property, you can just do

for col in table.columns:
    for cell in col.cells:
        cell.paragraphs[0].style = 'My Center Aligned Style'

If you have more advanced contents, you will have to add another loop to your function:

for col in table.columns:
    for cell in col.cells:
        for par in cell.paragraphs:
            par.style = 'My Center Aligned Style'

You can easily stick this code into a function that will accept a table object and a style name, and format the whole thing.

Solution 2:[2]

Well, it seems that adding a paragraph works, but (oh, really?) it addes a new paragraph -- so in my case it wasn't an option. You could change the value of the existing cell and then change paragraph's alignment:

row[0].text = "hey, beauty"
p = row[0].paragraphs[0]
p.alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.CENTER

Actually, in the top answer this first "docx.enum.text" was missing :)

Solution 3:[3]

In my case I used this.

from docx.enum.text import WD_ALIGN_PARAGRAPH

def addCellText(row_cells, index, text):
    row_cells[index].text = str(text)
    paragraph=row_cells[index].paragraphs[0]
    paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
    font = paragraph.runs[0].font
    font.size= Pt(10)

def addCellTextRight(row_cells, index, text):
    row_cells[index].text = str(text)
    paragraph=row_cells[index].paragraphs[0]
    paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    font = paragraph.runs[0].font
    font.size= Pt(10)

Solution 4:[4]

From docx.enum.table import WD_TABLE_ALIGNMENT

table = document.add_table(3, 3)
table.alignment = WD_TABLE_ALIGNMENT.CENTER

For details see a link .

http://python-docx.readthedocs.io/en/latest/api/enum/WdRowAlignment.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mad Physicist
Solution 2 Павел Ходунов
Solution 3 Maciel Escudero Bombonato
Solution 4 4b0