python word 表格插入一行數據

import docx


def insert_row(path, table_n, row_index, s_col_index,e_col_index,content):
"""
插入行
:param path: 路徑
:param table_n: 第幾個表格
:param row_index: 插入到第幾行
:param s_col_index: 數據所在的列
:param e_col_index: 需要合併的列
:param content: 內容
:return:
"""
# 獲取文檔中的表格
doc = docx.Document(path)
tables = doc.tables
table = tables[table_n] # 假設插入行的表格是第一個表格

# 在指定位置插入一行
new_row = table.add_row().cells
for i, text in enumerate(content):
new_row[i].text = text

# 移動新插入的行到指定位置
rows = table.rows
rows[row_index]._element.getparent().insert(
rows[row_index]._element.getparent().index(rows[row_index]._element), rows[-1]._element
)
rows[-1]._element.getparent().remove(rows[-1]._element)

# 數據所在的行和列
cell = table.rows[row_index].cells[s_col_index]
# 需要合併的行和列
cell_span = table.rows[row_index].cells[s_col_index:e_col_index]
cell_span[0].merge(cell_span[-1])
doc.save(path)


content = ["11111"]
path = r'''cc.docx'''

insert_row(path, table_n=0, row_index=1,s_col_index=0,e_col_index=1,content=content)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章