Using xlrd to get list of excel values in python

▼魔方 西西 提交于 2019-12-08 03:26:15

问题


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?


回答1:


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))


来源:https://stackoverflow.com/questions/21560574/using-xlrd-to-get-list-of-excel-values-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!