8
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?

huba183
  • 83
  • 1
  • 1
  • 4
  • You may want to consider https://github.com/elapouya/python-docx-template if you plan to do a lot of styling. – click here Mar 24 '17 at 19:42

4 Answers4

12

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

3

Up there the solution really helped. I use it for a while. But I found a tiny problem:time. As your table grows bigger the time you cost to build the table getting longer. So I improve it. Cut two rounds. Here you are:

The code changes the whole table

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

When you cut two rounds you save the time

smilyface
  • 5,021
  • 8
  • 41
  • 57
dream-blue
  • 119
  • 3
3

Building on user7609283 answer, here is a short version to set a cell to bold (the cell must contain text before applying format as it looks for the first paragraph):

    row_cells = table.add_row().cells
    row_cells[0].text = "Customer"
    row_cells[0].paragraphs[0].runs[0].font.bold = True
0

This font change applies to all cells of a table and is streamlined. All cells must contain text before being formatted or an index out of range error is thrown:

for row in table.rows:
    for cell in row.cells:
        cp = cell.paragraphs[0].runs
        cp[0].font.size = Pt(14)

This next font change applies to a single cell as wanted, in this case the top left cell:

tc = table.cell(0, 0).paragraphs[0].runs
tc[0].font.size = Pt(14)
PhilipBert
  • 25
  • 1
  • 3