首页 > 解决方案 > Python Docx 模块在随后添加到文档时合并表

问题描述

我正在使用python-docx模块和 python 3.9.0 使用 python 创建 word docx 文件。我遇到的问题如下:

A)我定义了一个名为的表格样式my_table_style

B)我打开我的模板,将一个该样式的表格添加到我的文档对象中,然后使用以下代码存储创建的文件:

import os
from docx import Document

template_path = os.path.realpath(__file__).replace("test.py","template.docx")
my_file = Document(template_path)

my_file.add_table(1,1,style="my_table_style").rows[-1].cells[0].paragraphs[0].add_run("hello")

my_file.save(template_path.replace("template.docx","test.docx"))

当我现在打开 test.docx 时,一切都很好,一张桌子有一排说“你好”。

现在,当我使用此语法创建其中两个表时:

import os
from docx import Document

template_path = os.path.realpath(__file__).replace("test.py","template.docx")
my_file = Document(template_path)

my_file.add_table(1,1,style="my_table_style").rows[-1].cells[0].paragraphs[0].add_run("hello")
my_file.add_table(1,1,style="my_table_style").rows[-1].cells[0].paragraphs[0].add_run("hello")

my_file.save(template_path.replace("template.docx","test.docx"))

我没有得到两张桌子,每张桌子都有一行说“你好”,而是一张桌子有两行,每张桌子都说“你好”。然而,根据 ,格式是正确的,my_table_style因此 python-docx 似乎合并了两个随后添加的具有相同表格样式的表格。这是正常行为吗?我怎样才能避免这种情况?

干杯!

提示:

当我print(len(my_file.tables))用来打印 my_file 中存在的表格数量时,我实际上得到了“2”!另外,当我更改第二add_table行中使用的样式时,效果很好,所以这似乎与使用相同样式的事实有关。任何想法,任何人?

标签: pythonpython-3.xpython-docx

解决方案


好吧,所以我想通了,执行上述操作似乎是 Word 的默认行为。我在文件中手动创建了一个表格样式 my_custom_style,在该template.docx文件中我自定义了表格边框线等以具有我想要的格式,就好像我有两个表格一样。我没有使用两个add_table()语句,而是使用

new_table = my_file.add_table(1,1,style = "my_custom_style")
first_row = new_table.rows[-1]
second_row = new_table.add_row()

(您实际上可以通过 python-docx 访问模板中定义的表格样式,只需使用您在用于打开Document对象的 word 模板文件中手动创建表格样式的表格样式名称即可。只需确保勾选“添加将此表格样式保存到 Word 模板”选项在 Word 中保存样式时,它应该都可以工作)。现在一切正常。


推荐阅读