from docx import Document
from copy import deepcopydef insert_row_after_specific_value(doc, table_index, column_header, target_value, new_row_data):# 加载文档# doc = doc_path# 检查表格索引是否有效if table_index >= len(doc.tables):print("文档中没有足够的表格。")return# 获取指定表格table = doc.tables[table_index]# 找到列标题“单位类别”的索引column_index = Nonefor i, cell in enumerate(table.rows[0].cells):if cell.text.strip() == column_header:column_index = ibreakif column_index is None:print("未找到指定的列标题:", column_header)return# 遍历表格中的行,找到符合条件的行insert_index = Nonefor i, row in enumerate(table.rows):if i == 0: # 跳过标题行continueif row.cells[column_index].text.strip() == target_value:insert_index = i + 1 # 插入位置在找到的行之后breakif insert_index is not None:# 在找到的行下方插入新行if len(new_row_data) > 0:for _i, d in enumerate(new_row_data):new_row = Noneif _i > 0:new_row = deepcopy(table.rows[insert_index - 1])table.rows[insert_index + _i - 1]._tr.addprevious(new_row._element)if _i == 0:new_row = table.rows[insert_index - 1]# 设置新行的数据for j, data in enumerate(new_row_data[_i]):if j < len(new_row.cells):new_row.cells[j + 1].text = str(data)else:# 如果新数据比现有单元格多,则忽略多余的数据breakelse:print("未找到符合条件的行。")return doc