Home » excel » Using xlrd to get list of excel values in python

Using xlrd to get list of excel values in python

Posted by: admin May 14, 2020 Leave a comment


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?

How to&Answers:
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))