I am relatively new to python-docx. I am trying to change the line spacing of a table in an existing document but it changes the line spacing of all the tables in the document.
Here is a minimal, reproducible example, creating from scratch a document with three tables:
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)
Output:
0 None
1 None
2 None
Then I try to change the line spacing only in the final 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)
Output:
0 88900
1 88900
2 88900
You can see it has changed the line spacing for all of the tables - they are all now 7 pt (12 point is 152400
). If I try to change the reset the line spacing in the other tables, all the tables are updated with whatever the last value to be changed is.
Here is my session info:
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
Is this a bug or am I doing something wrong?