Search code examples
pythonpython-docx

search string and replace using python-docx library


i would like to search a word and replace it with table. the following code is just for strings:

def paragraph_replace(self, search, replace):
    searchre = re.compile(search)
    for paragraph in self.paragraphs:
        paragraph_text = paragraph.text
        if paragraph_text:
            if searchre.search(paragraph_text):
                paragraph.text = re.sub(search, replace, paragraph_text)
    return paragraph_text

is there a way of replace it with table?


Solution

  • A table, like a paragraph, is a block-level content item, and the two can only appear as peers. So you cannot insert a table "in" a paragraph. You can only have a table "between" two paragraphs (or at the beginning or end of course).

    Something like this might do the trick for you until we can get this feature added to the library:

    table = document.add_table(...)
    p = paragraph_to_insert_before._p
    p.addprevious(table._tbl)
    

    The ._p and ._tbl properties are the lxml elements underlying the Paragraph and Table objects respectively. The addprevious() method is an lxml method that in this case moves the <w:tbl> element to be the preceding peer of the paragraph. You can substitute addnext() if you want it after the paragraph.

    It's a bit of a filthy hack but perhaps enough to get you by until we add that feature to the library. Let us know if it works for you :)