python-pptx:获取当前单元格的row_idx和col_idx值

python-pptx: Get row_idx and col_idx values of current cell

我目前正在做一个项目,我需要根据它的文本内容定位一个单元格,然后为它右边的单元格初始化一个单元格对象。

目前这是我的功能:

from pptx import Presentation

pptx = "path-to-my-pptx"

def update_table():
    prs = Presentation(pptx)
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_table:
                for cell in shape.table.iter_cells():
                    if cell.text == "string-im-looking-for":
                        ### get the current cell's row and col values
                        row = cell.row_idx
                        col = cell.col_idx
                        ### the cell next to it should logically be 
                        next_cell = shape.table.cell(row, col+1) 

文档本身在 _Cell 对象上提到了 col_idx 和 row_idx 方法: https://python-pptx.readthedocs.io/en/latest/user/table.html#a-few-snippets-that-might-be-handy

但是我得到: AttributeError: '_Cell' 对象没有属性 'row_idx'

有人知道我可能哪里出错了吗?或者我如何将 row_idx 和 col_idx 方法添加到 pptx 包的 table.py 文件中的 _Cell 对象?

非常感谢。

只是以不同的方式迭代以跟踪循环中的那些:

for row_idx, row in enumerate(table.rows):
    for col_idx, cell in enumerate(row.cells):
        print("%r is cells[%d][%d]" % (cell, row_idx, col_idx))

没关系!我通过将以下内容插入 tables.py _Cell 对象(大约第 184 行)找到了修复:

@property
def row_idx(self):
    return self._tc.row_idx

@property
def col_idx(self):
    return self._tc.col_idx

现在可以通过以下方式检索单元格 x 和 y 坐标:

x = cell.col_idx
y = cell.row_idx

希望这对其他人有帮助!