django-rest-framework-csv
django-rest-framework-csv copied to clipboard
XLSParser
And here is the parser: parsers.py
import xlrd
class HierarchicalXLSParser(HierarchicalCSVParser):
"""
Parses CSV serialized data.
The parser assumes the first line contains the column names.
"""
media_type = 'application/vnd.ms-excel'
def parse(self, stream, media_type=None, parser_context=None):
book = xlrd.open_workbook(file_contents=stream)
sheet = book.sheet_by_index(0)
data = []
header = []
try:
for row_index in range(sheet.nrows):
row = []
for col_index in range(sheet.ncols):
if row_index==0:
header.append(sheet.cell(row_index,col_index).value)
else:
row.append(sheet.cell(row_index,col_index).value)
if row_index!=0:
row_data = dict(zip(header, row))
hierarchical_data = self._csv_convert(row_data)
data.append(hierarchical_data)
return data
except Exception as exc:
raise ParseError('HierarchicalXLS parse error - %s' % str(exc))