python-docx center table content

4.9k views Asked by At

I've just started using python-docx and I'm trying to center the contents of my table. I have:

table = document.add_table(rows=1, cols=1)
tableHeader = table.rows[0].cells
tableHeader[0].text = 'test'
row_cells = table.add_row().cells
row_cells[0].text = 'example'
table.style = 'MediumGrid3'

which outputs a table with the header test and the text example.

I thought table.alignment = 1 would work, but it does nothing.

So how do I align all the text to the center?

3

There are 3 answers

1
scanny On BEST ANSWER

The setting you're asking about isn't yet supported in python-docx.

If you add an issue for it, perhaps titled: "feature: Table.alignment", to the GitHub issues list, we'll add it to the backlog. https://github.com/python-openxml/python-docx/issues

If you haven't come across it yet, you can find the documentation for python-docx here: http://python-docx.readthedocs.org/en/latest/

0
Noam Manos On

Here's how to do table cell vertical alignment:

import traceback
from docx.oxml.shared import OxmlElement, qn

def set_cell_vertical_alignment(cell, align="center"): 
    try:   
        tc = cell._tc
        tcPr = tc.get_or_add_tcPr()
        tcValign = OxmlElement('w:vAlign')  
        tcValign.set(qn('w:val'), align)  
        tcPr.append(tcValign)
        return True 
    except:
        traceback.print_exc()             
        return False
0
kampfe20 On

use paragraph in cell. like this:

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH

table = document.add_table(rows=1, cols=1)
cell = table.rows[0].cells[0]
cell_paragraph = cell.paragraphs[0]
cell_paragraph.text = 'test'
cell_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER