问题描述
我对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,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,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.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
这是错误还是我做错了什么?
解决方法
样式就像设置一次格式模板,然后将其应用于想要获得一致格式的任意数量的文档对象。应用了该样式的每个对象都会获得相同的格式设置集。调整表格样式(所有表格似乎都在共享)时,您会得到准确的结果。
我想您想做的是仅在相关表格的段落上直接设置段落行距。您可以设置新的段落样式,然后根据需要将其应用于这些段落。