使用xlrd获取python中的excel值列表 [英] Using xlrd to get list of excel values in python
问题描述
我正在尝试在Excel工作表的列中读取值列表.但是,列的长度每次都不同,所以我不知道列表的长度.如何获取python读取列中的所有值并使用xlrd在单元格为空时停止?
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?
推荐答案
for i in range(worksheet.nrows):
将遍历工作表中的所有行
will iterate through all the rows in the worksheet
例如,如果您对第0列感兴趣
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))
然后您可以使用itertools.takewhile进行懒惰的评估...在您第一个空值开始时将停止...如果您只想在获得第一个空值后停止就可以提供更好的性能
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))
这篇关于使用xlrd获取python中的excel值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!