David542
David542

Reputation: 110093

Get cell by column name using xlrd

If I have two rows in an Excel (.xls) sheet, like a key-value pair, is there a way to get the value (row1) by entering in the key (row0) in xlrd?

For example, if I have (0,0) = COLOR and (1,0) = RED, how would I do something like:

value = sh.col_values("COLOR") ?

The closest I have been able to find is sh.col_values(int), but that only allows me to enter in an index.

Upvotes: 4

Views: 10702

Answers (1)

agf
agf

Reputation: 176740

You have to search down the column until you find COLOR then get the value in the next row.

from itertools import product

def value_from_key(sheet, key):
    for row_index, col_index in product(xrange(sheet.nrows), xrange(sheet.ncols)):
        if sheet.cell(row_index, col_index).value == key:
            return sheet.cell(row_index+1, col_index).value

value = value_from_key(sheet, 'COLOR')

If you knew the keys were in even or odd rows you could use xrange(0, sheet.nrows, 2) or xrange(1, sheet.nrows, 2) instead.

Edit: Updated to search columns as well.

Upvotes: 3

Related Questions