0

I am using the python-docx library to create a docx file that contains text and a table right after it. I want to set the text size to 12 and table size to 9 point using styles. But the size of all the text, including the text in the table cells, is set to 12. I know I can use another loop based approach to solve this problem, but I like to use styles, is this possible?

Style approach (it dosen't work):

result 1

import random
from docx import Document
from docx.shared import Pt

doc = Document()
normal_style = doc.styles['Normal']
normal_style.font.size = Pt(12)  # SETTING FONT SIZE 12 FOR TEXT
paragraph = doc.add_paragraph("This is some introductory text.", style='Normal')
num_rows = 5
num_cols = 4
table = doc.add_table(rows=num_rows, cols=num_cols)

for row in table.rows:
    for cell in row.cells:
        cell.text = str(random.randint(1, 100))

table.style = 'TableGrid'
table_grid_style = doc.styles['TableGrid']
table_grid_style.font.size = Pt(9)  # SETTING FONT SIZE 9 FOR TABLES!

doc.save('random_table_with_intro_text.docx')

Other loop-based approach that works fine, but I dislike it:

results 2

import random
from docx import Document
from docx.shared import Pt

doc = Document()
paragraph = doc.add_paragraph("This is some introductory text.")
run = paragraph.runs[0]
run.font.size = Pt(12)
num_rows = 5
num_cols = 4

table = doc.add_table(rows=num_rows, cols=num_cols)
for row in table.rows:
    for cell in row.cells:
        paragraph = cell.paragraphs[0]
        run = paragraph.add_run(str(random.randint(1, 100)))
        run.font.size = Pt(9)
table.style = 'TableGrid'
doc.save('random_table_with_intro_text.docx')

Also, if I remove the code that adds the text above the table, it works (maybe I'm missing something):

import random
from docx import Document
from docx.shared import Pt

doc = Document()

num_rows = 5
num_cols = 4
table = doc.add_table(rows=num_rows, cols=num_cols)

for row in table.rows:
    for cell in row.cells:
        cell.text = str(random.randint(1, 100))

table.style = 'TableGrid'
table_grid_style = doc.styles['TableGrid']
table_grid_style.font.size = Pt(9)  # SETTING FONT SIZE 9 FOR TABLES!

doc.save('random_table_with_intro_text.docx')
2
  • You third script is same as first script. Commented May 21 at 12:53
  • @AdiosGringo No, it is not the same. I deleted the code that adds text in the third script to show that using styles you can set appropriate font size in tables. You can run it and check the results (a docx file appears in the folder with the script). Commented May 21 at 12:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.