Python-docx:更改一个表的行距会更改所有表中的行距

问题描述 投票:0回答:1

我正在尝试更改现有文档中表格的行距,但它会更改文档中所有表格的行距。

这是一个可重现的示例,创建一个包含三个表的文档:

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 = 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

它改变了所有表格的行距 - 它们现在都是 7 磅(12 磅是

152400
)。如果我尝试重置其他表格中的行距,所有表格都会更新为该值。

这是我的会话信息:

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

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

python openxml python-docx
1个回答
3
投票

样式就像一个格式模板,您设置一次,然后应用到您想要获得一致格式的任意多个文档对象。应用该样式的每个对象都会获得相同的格式设置集。当您调整表格样式(所有表格似乎都共享)时,您将得到您所看到的准确结果。

我认为您想要做的是将段落行距直接设置在相关表格的段落上。您可以设置新的段落样式,然后根据需要将其应用到这些段落。

© www.soinside.com 2019 - 2024. All rights reserved.