mjumbewu / django-rest-framework-csv

CSV Tools for Django REST Framework
BSD 2-Clause "Simplified" License
364 stars 89 forks source link

XLSParser #23

Open cescp opened 9 years ago

cescp commented 9 years ago

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))