How can I add a table after a specific paragraph in a word document using python

75 Views Asked by At

I try to write in docx with python a table. Currently this table is placed at the end of the document, but i want to be placed after paragraph[85]. The word document I use is already filled up with data inside it like plane text or tables. Table picked up to be written in docx is from an excel file (this work as expected). The main problem is related to the place where the table is writted

def set_cell_margins(cell, **kwargs):
    """
    cell:  actual cell instance you want to modify
    usage:
        set_cell_margins(cell, top=50, start=50, bottom=50, end=50)

    provided values are in twentieths of a point (1/1440 of an inch).
    read more here: http://officeopenxml.com/WPtableCellMargins.php
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')

    for m in ["top", "start", "bottom", "end"]:
        if m in kwargs:
            node = OxmlElement("w:{}".format(m))
            node.set(qn('w:w'), str(kwargs.get(m)))
            node.set(qn('w:type'), 'dxa')
            tcMar.append(node)

    tcPr.append(tcMar)


def add_table_to_doc(document, df, heading, table_style='Table Grid'):
    """ Adds a table to a docx document """
    columns = list(df.columns)
    # add table
    table = document.add_table(rows=1, cols=len(columns), style=table_style)
    table.autofit = True
    # add columns if there is '_' then replace with space
    for col in range(len(columns)):
        set_cell_margins(table.cell(0, col), top=50, start=50, bottom=50, end=50)
        table.cell(0, col).text = columns[col].replace("_", " ").capitalize()
    # add data
    for i, row in enumerate(df.itertuples()):
        table_row = table.add_row().cells
        for col in range(len(columns)):
            set_cell_margins(table_row[col], top=50, start=50, bottom=50, end=50)
            table_row[col].text = str(row[col + 1])

    doc.add_paragraph("\n")
# Store in doc variable what is inside of this document
doc = docx.Document(path_to_docx)
# Write in release document the table with integrated tickets
hr_df = pd.read_excel(latest_file, engine="openpyxl")
hr_df = hr_df[['id', 'summary']]

text = "Changelog  " + lines[0] + " (Integrated CRs):"
add_text(doc, text + "\n\n")

add_table_to_doc(doc, hr_df.iloc[:100], 'test')
print(latest_file)

doc.save(path_to_docx)
doc.add_paragraph("\n")
0

There are 0 best solutions below