Search code examples
pythonms-worddocx

Docx - Replace element and set font-style?


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

enter image description here

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)

enter image description here

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

enter image description here

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


Solution

  • I think i found a solution for that - iterrating over the runs in the paragraph it seems that after replacement the style keeps the same:

    from docx import Document
        for idxPara, elemPara in enumerate(doc.paragraphs):
          for run in elemPara.runs:
            if "«Kunde»" in run.text:
              run.text = "Anderer Text"