gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:55:23 26 4
gpt4 key购买 nike

我对 python-docx 比较陌生。我正在尝试更改现有文档中表格的行距,但它更改了文档中所有表格的行距。
这是一个最小的、可重现的示例,从头开始创建一个包含三个表的文档:

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 pt(12 点是 152400)。如果我尝试更改其他表中的重置行间距,则所有表都会更新为要更改的最后一个值。
这是我的 session 信息:
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-docx:更改一个表的行间距会在所有表中更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63987532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com