cemshid
cemshid

Reputation: 43

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

I am currently working on a project where I need to locate a cell based on its text content, and then initialise a cell object for the cell immediately to the right of it.

Currently this is my function:

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) 

The docs themselves mention a col_idx and row_idx method on the _Cell object here: https://python-pptx.readthedocs.io/en/latest/user/table.html#a-few-snippets-that-might-be-handy

However I am getting: AttributeError: '_Cell' object has no attribute 'row_idx'

Anyone know where I may be going wrong? Or how I could add the row_idx and col_idx methods to the _Cell object in the pptx package's table.py file?

Thanks a lot.

Upvotes: 1

Views: 2608

Answers (2)

cemshid
cemshid

Reputation: 43

Nevermind! I found a fix by inserting the following into the tables.py _Cell object (approx. line 184):

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

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

cell x and y coords can now be retrieved by:

x = cell.col_idx
y = cell.row_idx

Hope this helps somebody else out there!

Upvotes: 1

scanny
scanny

Reputation: 28883

Just iterate differently to keep track of those in the loop:

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

Upvotes: 3

Related Questions