from docx import Document
from copy import deepcopy
def 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 = None
for i, cell in enumerate(table.rows[0].cells):
if cell.text.strip() == column_header:
column_index = i
break
if column_index is None:
print("未找到指定的列标题:", column_header)
return
# 遍历表格中的行,找到符合条件的行
insert_index = None
for i, row in enumerate(table.rows):
if i == 0: # 跳过标题行
continue
if row.cells[column_index].text.strip() == target_value:
insert_index = i + 1 # 插入位置在找到的行之后
break
if insert_index is not None:
# 在找到的行下方插入新行
if len(new_row_data) > 0:
for _i, d in enumerate(new_row_data):
new_row = None
if _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:
# 如果新数据比现有单元格多,则忽略多余的数据
break
else:
print("未找到符合条件的行。")
return doc