使用Python docx库匹配段落时无法添加新行并插入表格的问题
使用Python-docx匹配指定字符串后插入表格的问题及解决
问题说明
匹配到字符串Test criteria / Testkriterien后,想要在其下方插入表格,预期是表格位于两段文字之间独立显示;但实际效果是表格与后续文本混排,后续文本被挤入表格首单元格中。
原代码
from docx import Document from docx.shared import RGBColor from docx.oxml.ns import qn from docx.oxml import OxmlElement document = Document(r'D:\Reqquirement_doc\cb test automation\requirements and other documents\Template_Testreport_8PA3.1.docx') # 创建并填充表格 table = 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 # 设置单元格背景色 tblCell = cell._tc tblCellProperties = tblCell.get_or_add_tcPr() clShading = OxmlElement('w:shd') clShading.set(qn('w:fill'), "D5B076") tblCellProperties.append(clShading) # 填充表格数据行 for 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") tblCellProperties.append(clShading) # 遍历段落插入表格 for 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)
问题原因
原代码把表格元素直接追加到了目标段落(document.paragraphs[i+1])的内部元素中,导致表格成为该段落的一部分,后续文本自然会被纳入表格首单元格。
解决方法
需要将表格作为独立元素插入到文档的body中,放在匹配段落的下一个位置。可额外添加空段落来保证排版间距。
修改后的代码
from docx import Document from docx.shared import RGBColor from docx.oxml.ns import qn from docx.oxml import OxmlElement document = Document(r'D:\Reqquirement_doc\cb test automation\requirements and other documents\Template_Testreport_8PA3.1.docx') # 创建并填充表格 table = 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 # 设置表头单元格背景色 tblCell = cell._tc tblCellProperties = tblCell.get_or_add_tcPr() clShading = OxmlElement('w:shd') clShading.set(qn('w:fill'), "D5B076") tblCellProperties.append(clShading) # 填充表格数据行 for 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") tblCellProperties.append(clShading) # 遍历段落找到目标位置插入表格 for i, para in enumerate(document.paragraphs): if para.text == 'Test criteria / Testkriterien': # 获取文档body元素 body = document._body._body target_element = para._element # 在目标段落后插入空段落(用于调整间距) empty_para = OxmlElement('w:p') target_element.addnext(empty_para) # 在空段落后插入表格 empty_para.addnext(table._element) # 表格后再插入空段落(可选) empty_para2 = OxmlElement('w:p') table._element.addnext(empty_para2) 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)
内容的提问来源于stack exchange,提问作者sathwik
相关产品推荐
相关产品推荐

