From 1f619644763cf2733f559dfb87c2097087d476f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADt=20Star=C3=BD=20Novotn=C3=BD?= Date: Wed, 15 Oct 2025 14:48:41 +0200 Subject: [PATCH] Fix ValueError while accessing `cell._tc.bottom` See also . Co-authored-by: mepwang <6652450+mepwang@users.noreply.github.com> --- src/docx/oxml/table.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/docx/oxml/table.py b/src/docx/oxml/table.py index 9457da207..22aec711f 100644 --- a/src/docx/oxml/table.py +++ b/src/docx/oxml/table.py @@ -82,20 +82,21 @@ def tc_at_grid_offset(self, grid_offset: int) -> CT_Tc: Raises ValueError when this `w:tr` contains no `w:tc` with exact starting `grid_offset`. """ # -- account for omitted cells at the start of the row -- - remaining_offset = grid_offset - self.grid_before + if grid_offset < self.grid_before: + raise ValueError(f"no `tc` element at grid_offset={grid_offset}") + + cell_dict = dict() + cell_index = 0 for tc in self.tc_lst: - # -- We've gone past grid_offset without finding a tc, no sense searching further. -- - if remaining_offset < 0: - break - # -- We've arrived at grid_offset, this is the `w:tc` we're looking for. -- - if remaining_offset == 0: - return tc - # -- We're not there yet, skip forward the number of layout-grid cells this cell - # -- occupies. - remaining_offset -= tc.grid_span - - raise ValueError(f"no `tc` element at grid_offset={grid_offset}") + for _ in range(tc.grid_span): + cell_dict[cell_index] = tc + cell_index += 1 + + if grid_offset not in cell_dict: + raise ValueError(f"no `tc` element at grid_offset={grid_offset}") + + return cell_dict[grid_offset] @property def tr_idx(self) -> int: