user3204260
user3204260

Reputation: 115

Using xlrd to get list of excel values in python

I am trying to read a list of values in a column in an excel sheet. However, the length of the column varies every time, so I don't know the length of the list. How do I get python to read all the values in a column and stop when the cells are empty using xlrd?

Upvotes: 1

Views: 9537

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113940

for i in range(worksheet.nrows):

will iterate through all the rows in the worksheet

if you were interested in column 0 for example

c0 = [worksheet.row_values(i)[0] for i in range(worksheet.nrows) if worksheet.row_values(i)[0]]

or even better make this a generator

column_generator = (worksheet.row_values(i)[0] for i in range(worksheet.nrows))

then you can use itertools.takewhile for lazy evaluations... that will stop when you get your first empty... this will provide better performance if you just want to stop once you get your first empty value

from itertools import takewhile
print list(takewhile(str.strip,column_generator))

Upvotes: 4

Related Questions