答案 0 :(得分:0)
在xlrd docs中,没有办法做到这一点。而且在Python中,切片是一维的,但是表是二维的定义。例如,在numpy中,这个约束通过使用更复杂的索引函数来克服(参见Numpy Indexing)。
你可以像这样迭代单元格范围iteration protocol:
class CellRange:
def __init__(self, sheet, r1, r2, c1, c2):
self.sheet = sheet
self.c1 = c1
self.c2 = c2
self.r1 = r1
self.r2 = r2
self.cc = self.c1-1 # to get [0,0] item in first next()
self.rc = self.r1
def __iter__(self):
return self
def __next__(self):
self.cc += 1
if self.cc > self.c2:
self.cc = self.c1
self.rc += 1
if self.rc > self.r2:
raise StopIteration()
return self.sheet.cell_value(self.rc, self.cc)
或使用generator功能:
def CellRange(sheet, r1, r2, c1, c2):
cc = c1
rc = r1
while rc <= r2:
while cc <= c2:
yield sheet.cell_value(rc, cc)
cc += 1
rc += 1
cc = c1
用法示例:
for v in CellRange(tablesheet,2,5,3,7):
print(v)