Skip to content

Commit 0600221

Browse files
fix: Attempt 2 at fixing column width in MS Word (#81)
1 parent e2f67ee commit 0600221

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "cmi-docx"
3-
version = "0.6.12"
3+
version = "0.6.13"
44
description = "Additional tooling for Python-docx."
55
readme = "README.md"
66
requires-python = ">=3.12"

src/cmi_docx/declarative/document.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -911,6 +911,17 @@ def _apply_column_widths(
911911
) -> None:
912912
"""Apply fixed column widths to a python-docx table.
913913
914+
Word XML Elements & Attributes Referenced:
915+
w:tblW: Table Width property. Defines the overall width of the entire table.
916+
w:w: Width value attribute. Holds the numeric measurement for an element.
917+
w:type: Measurement unit type.
918+
w:tr: Table Row element.
919+
w:tc: Table Cell element.
920+
w:gridSpan: Grid span property. Dictates how many logical columns a horizontally
921+
merged cell spans.
922+
w:val: Value attribute.
923+
w:tcW: Table Cell Width property.
924+
914925
Args:
915926
tbl: The python-docx Table to modify.
916927
column_widths: List of widths in twips (DXA), one per column.
@@ -929,6 +940,26 @@ def _apply_column_widths(
929940
for index, width in enumerate(column_widths):
930941
tbl.columns[index].width = shared.Twips(width)
931942

943+
total_width = sum(column_widths)
944+
tblW = tbl._tbl.tblPr.find(qn("w:tblW")) # noqa: SLF001, N806
945+
if tblW is not None:
946+
tblW.set(qn("w:w"), str(total_width))
947+
tblW.set(qn("w:type"), "dxa")
948+
949+
for tr in tbl._tbl.findall(qn("w:tr")): # noqa: SLF001
950+
col_start = 0
951+
for tc in tr.findall(qn("w:tc")):
952+
gridSpan_el = ( # noqa: N806
953+
tc.tcPr.find(qn("w:gridSpan")) if tc.tcPr is not None else None
954+
)
955+
span = int(gridSpan_el.get(qn("w:val"))) if gridSpan_el is not None else 1
956+
cell_width = sum(column_widths[col_start : col_start + span])
957+
tcW = tc.tcPr.find(qn("w:tcW")) if tc.tcPr is not None else None # noqa: N806
958+
if tcW is not None:
959+
tcW.set(qn("w:w"), str(cell_width))
960+
tcW.set(qn("w:type"), "dxa")
961+
col_start += span
962+
932963

933964
def _pack_table_row(
934965
docx_doc: docx_document.Document,

0 commit comments

Comments
 (0)