Python-docx - How to change table font size?

huba183 picture huba183 · Mar 24, 2017 · Viewed 12.6k times · Source
table = document.add_table(rows=1, cols=1)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'

I have to change font size of text 'Qty' in table with one row and one column, how can I make it?

Answer

user7609283 picture user7609283 · Mar 25, 2017

You need to get the paragraph in the cell. From the documentation of python-docx:

3.5.2 _Cell objects:
class docx.table._Cell (tc, parent)

paragraphs
List of paragraphs in the cell. A table cell is required to contain at least one block-level element and end with a paragraph. By default, a new cell contains a single paragraph. Read-only

Reference: python-docx Documentation - Read the Docs

The code:

To change font size of text 'Qty'

paragraph =hdr_cells[0].paragraphs[0]
run = paragraph.runs
font = run[0].font
font.size= Pt(30) # font size = 30

To change font size of the whole table:

for row in table.rows:
    for cell in row.cells:
        paragraphs = cell.paragraphs
        for paragraph in paragraphs:
            for run in paragraph.runs:
                font = run.font
                font.size= Pt(30)

Reference of how to access paragraphs in a table: Extracting data from tables