user1182090
user1182090

Reputation: 301

How to get Excel cell row and col based on cell value using python

How to identify cell row and cell col based on xl cell value in python...

sheet.cell(row,col) gives value but if we have value then how to get that corresponding row and col value of the shell

i searched but i could know how to identify cell details based on cell value..

pls help me thanks in advance

Upvotes: 1

Views: 11147

Answers (1)

Anthon
Anthon

Reputation: 76882

You will have to iterate over the worksheets, then over the rows in a worksheet and then over the cells in a row. You have to keep track of the row and column number as the xlrd Cell class does not seem to store that:

import sys
import xlrd

_ordA = ord('A')

def find_val_in_workbook(wbname, val):
    wb = xlrd.open_workbook(wbname)
    for sheet in wb.sheets():
        for rowidx in range(sheet.nrows):
            row = sheet.row(rowidx)
            for colidx, cell in enumerate(row):
                if cell.ctype != 2:
                    continue
                if cell.value != val:
                    continue
                if colidx > 26:
                    colchar = chr(_ordA + colidx / 26)
                else:
                    colchar = ''
                colchar += chr(_ordA + colidx % 26)
                print '{} -> {}{}: {}'.format(sheet.name, colchar, rowidx+1, cell.value)

find_val_in_workbook(sys.argv[1], float(sys.argv[2]))

call the script with the name of the .xls file and the value to search for

Upvotes: 1

Related Questions