簡體   English   中英

使用 python docx 替換 Word 文檔中的現有表格

[英]Replace existing table in Word doc using python docx

我有一個包含以下表格的 Word 文檔:

doc = Document('doc_generator.docx')
print(doc.tables)

[0x0000017E8B2A0D68 處的 docx.table.Table 對象,0x0000017E8B2A0198 處的 docx.table.Table 對象]

我正在嘗試用新表替換現有表之一。 我所做的是:

doc.tables[0] = new_table

new_table 是一個實際的 Word docx 表,即運行:

type(new_table)

返回:

文檔.table.Table

如果我然后嘗試通過以下方式保存更新的文檔:

doc.save('Updated.docx')

該表仍未更新。 如果相反,我運行一個命令,例如:

doc.tables[0].add_row()

該表格實際上是在 Word 文檔中更新的。 問題似乎是我的賦值語句。 知道如何解決這個問題嗎? 我確實想通過 python-docx 用新表替換現有表,而不是編輯或更新。 提前致謝。

您可以對父 xml 對象使用 .replace 方法:

doc.element.body.replace(old_table._element, new_table._element)

'old_table' 和 'new_table' 都是 docx.table.Table 對象。 ._element 屬性訪問文檔 xml 結構中的表對象。

如果 doc.element.body 不是表格的父元素,您可以使用以下方法找到父元素:

old_table._element.getparent()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM