问题描述
我目前正在一个项目中,需要根据其文本内容定位一个单元格,然后立即在其右侧初始化该单元格的单元格对象。
当前,这是我的功能:
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
希望这可以帮助其他人!