Need a help with below issue,
I have an issue adding a new line and by appending table data using python docx library by matching a string.Document:Document imageCode:Code
Expected result: I would like to append a table in between two paragraphs
My result: Table added along with a string available next to matched string, means that string is also added in my table first cell along with first cell data(row 0, column 0).
Please take a look at images, i would like to add new lines before and after matching a string and appending table.
My code below:
from docx import Documentfrom docx.shared import RGBColorfrom docx.oxml.ns import qnfrom docx.oxml import OxmlElementdocument = Document(r'D:\Reqquirement_doc\cb test automation\requirements and other documents\Template_Testreport_8PA3.1.docx')# Create and populate the table before the condition matchtable = document.add_table(rows=1, cols=len(post(read_only).columns))table.style = 'Table Grid'for x, col_name in enumerate(post(read_only).columns): cell = table.cell(0, x) cell.text = col_name # Set background color for cells tblCell = cell._tc tblCellProperties = tblCell.get_or_add_tcPr() clShading = OxmlElement('w:shd') clShading.set(qn('w:fill'), "D5B076") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E} tblCellProperties.append(clShading)# Iterate over the rows and columns of the tablefor x, row in (post(read_only).iterrows()): new_row = table.add_row().cells for y, val in enumerate(row): cell = new_row[y] cell.text = str(val) tblCell = cell._tc tblCellProperties = tblCell.get_or_add_tcPr() clShading = OxmlElement('w:shd') clShading.set(qn('w:fill'), "F6EFE3") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E} tblCellProperties.append(clShading)# Iterate over the paragraphs in the documentfor i in range(len(document.paragraphs)): if document.paragraphs[i].text == 'Test criteria / Testkriterien': document.paragraphs[i+1].add_run().add_break() document.paragraphs[i+1]._element.append(table._element) break modified_file_path = r'D:\Reqquirement_doc\cb test automation\requirements and other documents\Template_Testreport_8PA3.1_modified.docx'document.save(modified_file_path)