[Python] Docx - Replace element and set font-style?

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    i want to replace some paragraph-text in this docx-file:

    [​IMG]

    This works generally fine using this code:

    from docx import Document
    from docx.shared import Pt
    file = "template.docx"
    doc = Document(file)
    for idxPara, elemPara in enumerate(doc.paragraphs):
    if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"
    doc.save('TEST.docx')


    The output looks now like this: (everything is ok but i want to change the font-style)

    [​IMG]

    So i tried this code:

    from docx import Document
    from docx.shared import Pt

    file = "template.docx"
    doc = Document(file)

    style = doc.styles['Normal']
    font = style.font
    font.name = 'Corbel'
    font.size = Pt(10)

    for idxPara, elemPara in enumerate(doc.paragraphs):
    if "«Kunde»" in elemPara.text:
    doc.paragraphs[idxPara].style = doc.styles['Normal']
    doc.paragraphs[idxPara].text = "Anderer Text für Kunde"

    doc.save('TEST.docx')


    but unfortunately with this the style seems to work now - but the text in the paragraph is for whatevery reason on another position

    [​IMG]

    How can i change the paragraph and also set the style of this paragraph?

    Continue reading...

Compartilhe esta Página