【问题标题】:Python - Insert pandas data frame in between of the documentPython - 在文档之间插入熊猫数据框
【发布时间】:2022-06-10 17:05:05
【问题描述】:

我有一个pandas 数据框,我想将它插入到word document 之间。比方说-

  • 第 1 节

这是测试word文档

在此处插入表格

  • 第 2 节

表格应该插入到第 2 节之前。

应该插入 Pandas 数据框来代替 insert table here

我检查了python-docx,我们可以很容易地插入表格,但该表格将插入到文档的末尾。

我们可以使用 python-docx 在文档之间插入表格吗?如果没有,有人可以建议我可以用来实现此功能的其他库。

【问题讨论】:

  • 这个问题 (Add an image in a specific position in the document (.docx)?) 解决了如何在文本之间而不是最后放置图片 - 相同的答案可能会延续到您的案例中?
  • 尝试了上述方法,收到错误消息table = r.add_table(rows=2, cols=3) AttributeError: 'Run' object has no attribute 'add_table'

标签: python ms-word word python-docx aspose.words


【解决方案1】:

您可以使用 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 bookmarksworking 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)

【讨论】:

  • 我必须在现有文档中添加书签。考虑上面的单词示例,“在此处插入表格”中需要书签。当我使用您的代码 sn-p 时,它会在文档顶部添加表格。
  • 我已经更新了答案
  • 太棒了..这工作正常。我还有另一个要求,即从另一个文档复制内容并粘贴到文档的特定位置,保持格式不变。假设我们要插入另一个文档的内容来代替“在此处插入文本”,然后创建一个表格。
  • 您可以使用 DocumentBuilder.insert_document 方法实现此目的。查看更新后的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2019-05-01
  • 2019-01-25
  • 2015-08-27
  • 1970-01-01
相关资源
最近更新 更多