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

我目前正在开发一个项目,我需要根据单元格的文本内容来定位单元格,然后为紧邻其右侧的单元格初始化一个单元格对象。


目前这是我的功能:


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' object has no attribute 'row_idx'


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


多谢。


小唯快跑啊
浏览 137回答 2
2回答

慕运维8079593

只需进行不同的迭代来跟踪循环中的那些: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))

MMTTMM

没关系!我通过将以下内容插入到tables.py _Cell 对象中找到了修复方法(大约第184行):@propertydef row_idx(self):    return self._tc.row_idx@propertydef col_idx(self):    return self._tc.col_idx现在可以通过以下方式检索单元格 x 和 y 坐标:x = cell.col_idxy = cell.row_idx希望这对其他人有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python