Python-docx:更改一个 table 的行间距会在所有 table 中更改它

Python-docx: Changing line spacing for one table changes it in all tables

我对 python-docx 比较陌生。我正在尝试更改现有文档中 table 的行距,但它会更改文档中所有 table 的行距。

这是一个最小的、可重现的例子,从头开始创建一个包含三个 table 的文档:

from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.enum.text import WD_LINE_SPACING

document = Document()

# Some sample text to add to tables
records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)

# Create table 0
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

document.add_page_break()

# Create table 1
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

# Create table 2
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

# Print line spacing for all tables 
for index, table in enumerate(document.tables):
    print(index, table.style.paragraph_format.line_spacing)

输出:

0 None
1 None
2 None

然后我尝试只在最后更改行间距 table:

table = document.tables[2]
table.style.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY
table.style.paragraph_format.line_spacing = Pt(7)

# Print line spacing for all tables
for index, table in enumerate(document.tables):
    print(index, table.style.paragraph_format.line_spacing)

输出:

0 88900
1 88900
2 88900

您可以看到它已经更改了所有 table 的行距 - 它们现在都是 7 磅(12 磅是 152400)。如果我尝试更改重置其他 table 中的行间距,则所有 table 都会更新为要更改的最后一个值。

这是我的会话信息:

Session info --------------------------------------------------------------------
Platform: Windows-7-6.1.7601-SP1 (64-bit)
Python: 3.7
Date: 2020-09-21
Packages ------------------------------------------------------------------------
python-docx==0.8.10
reprexpy==0.3.0

这是一个错误还是我做错了什么?

样式就像您设置一次的格式模板,然后根据您的需要将其应用于尽可能多的文档对象以获得一致的格式。应用了该样式的每个对象都会获得相同的格式设置集。当您调整 table 样式(所有 table 似乎都共享)时,您会得到您所看到的结果。

我想你要做的是直接在有问题的 table 段落上设置段落行距。如果需要,您可以设置新的段落样式并将其应用于那些段落。