Search code examples
pythonpython-3.xdocxpython-docx

read text from left most cell only


I have a lot of tables in a docx file and I'm trying to get text from cells from first columns.

I have this code for searching in full rows

for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                result = ReqRegex.search(paragraph.text)
                if result:
                    file.write(result.group()+"\n")

but I'm trying to change it to check only first columns

for table in doc.tables:
    for column in table.columns:
        for cell in table.column_cells(0):
            for paragraph in cell.paragraphs:
                result = ReqRegex.search(paragraph.text)
                if result:
                    file.write(result.group()+"\n")

Can you tell me what can I change to make this code work?


Solution

  • Finally I have solved my problem. Maybe it will be useful for someone

    for table in doc.tables:
        rowNo = 0
        for row in table.rows:
            columnNo = 0
            for cell in row.cells:
                columnNo += 1
                for paragraph in cell.paragraphs:
                    result = ReqRegex.search(paragraph.text)
                    if columnNo == 1:
                        print(cell.text)
                        if result:
                            file.write(result.group()+"\n")
            rowNo += 1