-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyxl.py
57 lines (43 loc) · 1.38 KB
/
pyxl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import xlrd
def colmap(sheet):
idxs = range(sheet.ncols)
names = map(str, sheet.row_values(0))
return { pair[1]: pair[0] for pair in zip(idxs, names) }
def sheets(wb):
return [Sheet(wb.sheet_by_index(i)) for i in range(wb.nsheets)]
class Sheet:
def __init__(self, sheet):
self.current = 1
self.sheet = sheet
self.colmap = colmap(self.sheet)
self.hdr = self.sheet.row_values(0)
def __getitem__(self, row):
if type(row) == str:
return self.sheet.col_values(self.colmap[row], start_rowx=1)
if type(row) == tuple:
row, col = row
return self.sheet.cell(row, col).value
else:
return self.sheet.row_values(row)
def __iter__(self):
return self
def next(self):
if self.current >= self.sheet.nrows:
current = 1
raise StopIteration
else:
data = self.sheet.row_values(self.current)
self.current += 1
return data
def __len__(self):
return self.sheet.nrows
class Pyxl:
def __init__(self, fname):
self.wb = xlrd.open_workbook(fname)
self.sheets = sheets(self.wb)
def __getitem__(self, idx):
return self.sheets[idx]
def __iter__(self):
return self.sheets.__iter__()
def __len__(self):
return len(self.sheets)