python - 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
行中使用的样式时,效果很好,所以这似乎与使用相同样式的事实有关。任何想法,任何人?
解决方案
好吧,所以我想通了,执行上述操作似乎是 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 中保存样式时,它应该都可以工作)。现在一切正常。
推荐阅读
- java - Spring Boot ConnectException 没有被捕获
- postgresql - 使用 Terraform 进行 AWS RDS IAM 身份验证
- css - SVG 图像未与周围元素对齐/像素完美(尤其是动画时不和谐!)
- html - 如何将图像的高度等距扩展到其全宽容器之外?
- node.js - 执行文件后在 CLI 上继续
- c# - 如何将 SQL 中的数据保存在列表中,然后仅使用 C# 而不使用 LINQ 找到最大值
- c++ - 如何设置我的解码函数以接收编码字符串?
- html5-canvas - Fabric js悬停不起作用
- visual-studio - 在 Visual Studio 2017 中保留“Docker Compose”设置
- ssas - 使用 MDX 查询从日期范围中获取特定日期的时间表