def parse_excel self data items sheets Parse goods from excel file par

 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
def parse_excel(self, data, items, sheets=[0]):
"""
Parse goods from excel file
@param data: raw data of excel file
@param items: list of tuples. Each tuple is number of name, price columns.
@param sheets: list of number of sheets where goods could be found.
"""
book = xlrd.open_workbook(file_contents=data, encoding_override='cp1251')
goods = []
for sheet_number in sheets:
sh = book.sheet_by_index(sheet_number)
for row_counter in xrange(sh.nrows):
row = sh.row(row_counter)
for name_col, price_col in items:
if len(row) > price_col:
if isinstance(name_col, (list, tuple)):
name = ', '.join(map(unicode, filter(None, [row[x].value for x in name_col])))
else:
name = row[name_col].value
price = row[price_col].value
if hasattr(self, 'price_column_handler'):
price = self.price_column_handler(price)
if name and price:
try:
price = float(price)
except ValueError:
pass
else:
goods.append({'name': name, 'price': price})
return goods