为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

小唯快跑啊 2023-08-08 09:50:01
我目前正在开发一个项目,我需要根据单元格的文本内容来定位单元格,然后为紧邻其右侧的单元格初始化一个单元格对象。目前这是我的功能:from pptx import Presentationpptx = "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 对象?多谢。
查看完整描述

2 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

只需进行不同的迭代来跟踪循环中的那些:


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))


查看完整回答
反对 回复 2023-08-08
?
MMTTMM

TA贡献1869条经验 获得超4个赞

没关系!我通过将以下内容插入到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

希望这对其他人有帮助!


查看完整回答
反对 回复 2023-08-08
  • 2 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信