Search code examples
python-docx

Adding words in bold to table using python-docx


I'm new here (and to python) so any feedback on my post is welcome.

I have some code which asks for an input and then adds it to an entry in various tables.

e.g

import docx
doc = docx.Document('ABC.docx')
length = len(doc.tables) 
name = input("What is your name?")
x = range(0,length)
for r in x:
    doc.tables[r].cell(0, 1).text = name + ": " + doc.tables[r].cell(0, 1).text
doc.save("ABC_.docx")

and this will take text like "I love you" and change it to "Bob: I love you", which is great. However, I'd like the Bob to appear in bold. How do I do that?


Solution

  • Not sure this is the perfect way to do this, but it works. Basically you store the current cell text in a variable then clear the cell. After that, get the first paragraph of the cell and add formatted runs of text to it, as follows:

    import docx
    
    name = input("What is your name?")
    
    doc = docx.Document('ABC.docx')
    length = len(doc.tables) 
    x = range(0,length)
    for r in x:
        celltext = doc.tables[r].cell(0, 1).text
        doc.tables[r].cell(0, 1).text = ""
        paragraph = doc.tables[r].cell(0, 1).paragraphs[0]
        paragraph.add_run(name).bold = True
        paragraph.add_run(": " + celltext)
    
    doc.save("ABC_.docx")
    

    Input:

    What is your name?NewCoder
    

    Result:

    enter image description here