您可以使用 Aspose.Words 轻松实现此目的。在您的情况下,您可以在需要插入表格的地方插入书签作为占位符,然后使用 DocumentBuilder 在书签处插入表格。例如看下面的简单代码:
import aspose.words as aw
# Move cursor to the bookmark
builder.move_to_bookmark("table")
# build a table
builder.start_table()
for i in range(5):
for j in range(5):
builder.insert_cell()
builder.write("Cell {0},{1}".format(i, j))
builder.end_row()
builder.end_table()
doc.save("C:\\Temp\\out.docx")
Aspose.Words for Python 文档以了解有关 working with bookmarks 和 working with tables 的更多信息。
更新:如果需要使用文本作为占位符,可以使用如下代码:
import aspose.words as aw
doc = aw.Document("C:\\Temp\\in.docx")
builder = aw.DocumentBuilder(doc)
# Search for a placeholder paragraph
paragraphs = doc.get_child_nodes(aw.NodeType.PARAGRAPH, True)
for para in paragraphs :
paraText = para.to_string(aw.SaveFormat.TEXT).strip()
if paraText == "insert table here":
# Move cursor to the paragraph
builder.move_to(para)
# build a table
builder.start_table()
for i in range(5):
for j in range(5):
builder.insert_cell()
builder.write("Cell {0},{1}".format(i, j))
builder.end_row()
builder.end_table()
# If required you can remove the placeholder paragraph.
para.remove()
# Save the result
doc.save("C:\\Temp\\out.docx")
在 .NET 和 Java 版本的 Aspose.Words 中,您可以使用 IReplacingCallback 来实现此功能,但在 Python 版本中,此功能尚不可用。 IReplacingCallback 允许在执行Range.Replace 操作时执行自定义操作。
除了表格,你可以插入另一个文档的内容,只需使用 DocumentBuilder.insert_document 方法。代码将如下所示:
# Move cursor to the paragrapg
builder.move_to(para)
# Insert conten of another document
builder.insert_document(aw.Document("C:\\Temp\\src.docx"), aw.ImportFormatMode.KEEP_SOURCE_FORMATTING)