[Python] Setting font size for text and tables using styles approach with python-docx library

Discussão em 'Python' iniciado por Stack, Maio 23, 2025.

  1. Stack

    Stack Membro Participativo

    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):

    [​IMG]

    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:

    [​IMG]

    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')

    Continue reading...

Compartilhe esta Página