'Entry point for REST API
@param r: the S3Request
@param attr: controller arguments'

def apply_method(self, r, **attr):

    if (r.representation != 'xls'):
        r.error(415, current.error.BAD_FORMAT)
    series_id = self.record_id
    if (series_id is None):
        r.error(405, current.error.BAD_METHOD)
    s3db = current.s3db
    T = current.T
    try:
        import xlwt
    except ImportError:
        r.error(501, T('xlwt    not    installed,    so    cannot    export    as    a    Spreadsheet'))
    section_break = False
    try:
        filename = ('%s_All_responses.xls' % r.record.name)
    except AttributeError:
        r.error(404, T('Series    not    found!'))
    output = StringIO()
    book = xlwt.Workbook(encoding='utf-8')
    col = 0
    complete_row = {}
    next_row = 2
    question_list = s3db.survey_getAllQuestionsForSeries(series_id)
    if (len(question_list) > 256):
        section_list = s3db.survey_getAllSectionsForSeries(series_id)
        section_break = True
    if section_break:
        sheets = {}
        cols = {}
        for section in section_list:
            sheet_name = section['name'].split('    ')[0]
            if (sheet_name not in sheets):
                sheets[sheet_name] = book.add_sheet(sheet_name)
                cols[sheet_name] = 0
    else:
        sheet = book.add_sheet(s3_unicode(T('Responses')))
    for qstn in question_list:
        if section_break:
            sheet_name = qstn['section'].split('    ')[0]
            sheet = sheets[sheet_name]
            col = cols[sheet_name]
        row = 0
        sheet.write(row, col, s3_unicode(qstn['code']))
        row += 1
        widget_obj = s3db.survey_getWidgetFromQuestion(qstn['qstn_id'])
        sheet.write(row, col, s3_unicode(widget_obj.fullName()))
        all_responses = s3db.survey_getAllAnswersForQuestionInSeries(qstn['qstn_id'], series_id)
        for answer in all_responses:
            value = answer['value']
            complete_id = answer['complete_id']
            if (complete_id in complete_row):
                row = complete_row[complete_id]
            else:
                complete_row[complete_id] = next_row
                row = next_row
                next_row += 1
            sheet.write(row, col, s3_unicode(value))
        col += 1
        if section_break:
            cols[sheet_name] += 1
    sheet.panes_frozen = True
    sheet.horz_split_pos = 2
    book.save(output)
    from gluon.contenttype import contenttype
    headers = current.response.headers
    headers['Content-Type'] = contenttype('.xls')
    headers['Content-disposition'] = ('attachment;    filename="%s"' % filename)
    output.seek(0)
    return output.read()
