Beispiel #1
0
    def get(self, request):
        lendings = LendingFilter(request.GET,
                                 queryset=Lending.objects.all()).qs
        if not lendings:
            return Response(status=204)

        to_export = [[
            'id książki',
            'tytuł ksiązki',
            'utworzone przez',
            'status',
            'data utworzenia',
            'data modyfikacji',
        ]]
        for lending in lendings:
            first_history_entry = lending.history.filter(
                status=LendingHistory.RESERVED).first()
            to_export.append([
                lending.book.id,
                lending.book.title,
                first_history_entry.user.email,
                LendingHistory.STATUSES_MAP[lending.last_change.status],
                first_history_entry.created,
                lending.last_change.created,
            ])

        return excel.make_response_from_array(to_export,
                                              'xlsx',
                                              file_name='lendings.xlsx')
Beispiel #2
0
def report_organization_building(request, *args, **kwargs):
    var = request.GET.get('organization')
    if var:  # when have user selecting org
        org = get_object_or_404(OrganizationStructure, pk=var)
        organizations_child = OrganizationStructure.os_manager.filter_user(
            request.user)
        if org in organizations_child:  # user have perm on that organization ?
            organizations_child = org.get_descendants(include_self=True)
            labs = Laboratory.objects.filter(
                organization__in=organizations_child)
        else:
            if request.user.is_superuser:
                organizations_child = OrganizationStructure.os_manager.get_children(
                    var)
                labs = Laboratory.objects.filter(
                    organization__in=organizations_child)
            else:
                labs = Laboratory.objects.none()
    else:  # when haven't user selecting org
        organizations_child = OrganizationStructure.os_manager.filter_user(
            request.user)

        if organizations_child:
            labs = Laboratory.objects.filter(
                organization__in=organizations_child)
        else:
            if request.user.is_superuser:
                labs = Laboratory.objects.all()
            else:
                labs = Laboratory.objects.none()

    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        return django_excel.make_response_from_array(
            make_book_organization_laboratory(labs),
            fileformat,
            file_name="Laboratories.%s" % (fileformat, ))

    context = {
        #title of the report in verbose_name variable
        'verbose_name': "Organization laboratory report",
        'object_list': labs,
        'datetime': timezone.now(),
        'request': request,
        'laboratory': kwargs.get('lab_pk'),
    }
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="report_organization_libraries.pdf"'
    template = get_template('pdf/organizationlaboratory_pdf.html')
    html = template.render(context=context)

    pisaStatus = pisa.CreatePDF(html,
                                dest=response,
                                link_callback=link_callback,
                                encoding='utf-8')
    if pisaStatus.err:
        return HttpResponse('We had some errors with code %s <pre>%s</pre>' %
                            (pisaStatus.err, html))
    return response
Beispiel #3
0
def excel(request, id):
    import django_excel as excel
    import numpy as np
    import math
    lista = []
    aux=[]
    analise = AnaliseSensorial.objects.get(pk = id)
    perguntas = Pergunta.objects.filter(analise=analise.id)
    
    for pergunta in perguntas:  
        aux.append(pergunta.pergunta)
    
    for pergunta in perguntas:
        if pergunta.tipo == 'PIC':
            respostaIntencao = excelRetornaRespostas(IntencaoCompra,'PIC',id)
            lista.append(respostaIntencao)
        elif pergunta.tipo == 'PSN':
            respostaBoolean = excelRetornaRespostas(Boolean, 'PSN', id)
            lista.append(respostaBoolean)
        elif pergunta.tipo == 'PHD':
            respostaHedonica = excelRetornaRespostas(Hedonica, 'PHD', id)
            lista.append(respostaHedonica)
    lista = list(itertools.zip_longest(*lista))
    lista.append(aux)
    return excel.make_response_from_array(lista, 'xls')
Beispiel #4
0
def report_h_code(request, *args, **kwargs):
    form = H_CodeForm(request.GET)
    q = []
    if form.is_valid():
        q = form.cleaned_data['hcode']
    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        object_list = filter_by_user_and_hcode(
            request.user, q, function='convert_hcodereport_list')
        return django_excel.make_response_from_array(
            object_list,
            fileformat,
            file_name="hcode_report.%s" % (fileformat, ))
    else:
        object_list = filter_by_user_and_hcode(
            request.user, q, function='convert_hcodereport_table')

    template = get_template('pdf/hcode_pdf.html')

    context = {
        'object_list': object_list,
        'datetime': timezone.now(),
        'request': request,
    }

    html = template.render(context=context).encode("UTF-8")

    page = HTML(string=html, encoding='utf-8').write_pdf()

    response = HttpResponse(page, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="hcode_report.pdf"'
    return response
Beispiel #5
0
def generate_template(request, pk, export=False):
    inventory = get_object_or_404(Inventory, pk=pk)

    fields = [inventory.ordered_fields.keys()]

    return excel.make_response_from_array(fields,
                                          'xlsx',
                                          file_name="{}.xlsx".format(
                                              inventory.fields['name']))
Beispiel #6
0
def report_organization_building(request, *args, **kwargs):
    var = request.GET.get('organization')
    if var:  # when have user selecting org
        org = get_object_or_404(OrganizationStructure, pk=var)
        organizations_child = OrganizationStructure.os_manager.filter_user(
            request.user)
        if org in organizations_child:  # user have perm on that organization ?
            organizations_child = org.get_descendants(include_self=True)
            labs = Laboratory.objects.filter(
                organization__in=organizations_child)
        else:
            if request.user.is_superuser:
                organizations_child = OrganizationStructure.os_manager.get_children(
                    var)
                labs = Laboratory.objects.filter(
                    organization__in=organizations_child)
            else:
                labs = Laboratory.objects.none()
    else:  # when haven't user selecting org
        organizations_child = OrganizationStructure.os_manager.filter_user(
            request.user)

        if organizations_child:
            labs = Laboratory.objects.filter(
                organization__in=organizations_child)
        else:
            if request.user.is_superuser:
                labs = Laboratory.objects.all()
            else:
                labs = Laboratory.objects.none()

    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        return django_excel.make_response_from_array(
            make_book_organization_laboratory(labs),
            fileformat,
            file_name="Laboratories.%s" % (fileformat, ))

    context = {
        'object_list': labs,
        'datetime': timezone.now(),
        'request': request,
        'laboratory': kwargs.get('lab_pk')
    }

    template = get_template('pdf/organizationlaboratory_pdf.html')

    html = template.render(context=context).encode("UTF-8")

    page = HTML(string=html, encoding='utf-8').write_pdf()

    response = HttpResponse(page, content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="report_organization_libraries.pdf"'
    return response
Beispiel #7
0
def report_organization_building(request, *args, **kwargs):
    var = request.GET.get('organization')
    if var:  # when have user selecting org
        org = get_object_or_404(OrganizationStructure, pk=var)
        organizations_child = OrganizationStructure.os_manager.filter_user(
            request.user)
        if org in organizations_child:  # user have perm on that organization ?
            organizations_child = org.get_descendants(include_self=True)
            labs = Laboratory.objects.filter(
                organization__in=organizations_child)
        else:
            if request.user.is_superuser:
                organizations_child = OrganizationStructure.os_manager.get_children(
                    var)
                labs = Laboratory.objects.filter(
                    organization__in=organizations_child)
            else:
                labs = Laboratory.objects.none()
    else:  # when haven't user selecting org
        organizations_child = OrganizationStructure.os_manager.filter_user(
            request.user)

        if organizations_child:
            labs = Laboratory.objects.filter(
                organization__in=organizations_child)
        else:
            if request.user.is_superuser:
                labs = Laboratory.objects.all()
            else:
                labs = Laboratory.objects.none()

    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        return django_excel.make_response_from_array(
            make_book_organization_laboratory(labs), fileformat, file_name="Laboratories.%s" % (fileformat,))

    context = {
        'object_list': labs,
        'datetime': timezone.now(),
        'request': request,
        'laboratory': kwargs.get('lab_pk')
    }

    template = get_template('pdf/organizationlaboratory_pdf.html')

    html = template.render(
        context=context).encode("UTF-8")

    page = HTML(string=html, encoding='utf-8').write_pdf()

    response = HttpResponse(page, content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="report_organization_libraries.pdf"'
    return response
Beispiel #8
0
def viewPdfCsv(request, id):
    doc = Document.objects.get(id=id)
    pdfToTable(doc.document, docid=id)

    csvDoc = PdfCsv.objects.get(csvDoc_id=id)
    if PdfCsv.objects.filter(csvDoc_id=id).exists():
        path = csvDoc.csvFile.path
        f = open(path, 'r')

        csvRead = csv.reader(f, delimiter=",")
        data = [i for i in csvRead]

        filename = os.path.basename(path)
        sheet = excel.pe.Sheet(data)
        return excel.make_response_from_array(sheet, "csv", file_name=filename)
Beispiel #9
0
def listado_alfabetico(peticion):
    pagadas=Q(pago="Efectivo") | Q(pago="Transferencia")
    inscripciones=InscripcionJornadas.objects.filter(pagadas)
    lista=[]
    lista.append(
            ("Apellido1", "Apellido 2", "Nombre")
        )
    for i in inscripciones:
        if i.confirmada==True:
            confirmada="SI"
        else:
            confirmada="NO"
        lista.append(
            (i.apellido1, i.apellido2, i.nombre)
        )
    return excel.make_response_from_array(lista, 'xls', file_name="ListadoAlumnos.xls")
Beispiel #10
0
def report_limited_shelf_objects(request, *args, **kwargs):
    def get_limited_shelf_objects(query):
        for shelf_object in query:
            if shelf_object.limit_reached:
                yield shelf_object

    var = request.GET.get('pk')
    if var is None:
        if 'lab_pk' in kwargs:
            shelf_objects = ShelfObject.objects.filter(
                shelf__furniture__labroom__laboratory__pk=kwargs.get('lab_pk'))
        else:
            shelf_objects = ShelfObject.objects.all()
    else:
        shelf_objects = ShelfObject.objects.filter(pk=var)

    shelf_objects = get_limited_shelf_objects(shelf_objects)

    template = get_template('pdf/shelf_object_pdf.html')

    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        return django_excel.make_response_from_array(
            make_book_limited_reached(shelf_objects),
            fileformat,
            file_name="Laboratories.%s" % (fileformat, ))

    context = {
        'verbose_name': "Limited shelf objects",
        'object_list': shelf_objects,
        'datetime': timezone.now(),
        'request': request,
        'laboratory': kwargs.get('lab_pk')
    }
    html = template.render(context=context)
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="report_limited_shelf_objects.pdf"'
    pisaStatus = pisa.CreatePDF(html,
                                dest=response,
                                link_callback=link_callback,
                                encoding='utf-8')
    if pisaStatus.err:
        return HttpResponse('We had some errors with code %s <pre>%s</pre>' %
                            (pisaStatus.err, html))
    return response
Beispiel #11
0
def get_excel_inscripciones(peticion):
    inscripciones=get_inscripciones()
    lista=[]
    lista.append(
            ("NIF", "Apellido1", "Apellido 2", "Nombre","Especialidad",
             "Afiliado", "Años exp.", "Email", "Telefono", "Forma pago",
             "Confirma asist")
        )
    for i in inscripciones:
        if i.confirmada==True:
            confirmada="SI"
        else:
            confirmada="NO"
        lista.append(
            (i.nif, i.apellido1, i.apellido2, i.nombre,i.especialidad,
             i.afiliado, i.anios_exp, i.email, i.telefono,i.pago,
             confirmada)
        )
    return excel.make_response_from_array(lista, 'xls', file_name="InscripcionesJornadas.xls")
Beispiel #12
0
def report_limited_shelf_objects(request, *args, **kwargs):
    def get_limited_shelf_objects(query):
        for shelf_object in query:
            if shelf_object.limit_reached:
                yield shelf_object

    var = request.GET.get('pk')
    if var is None:
        if 'lab_pk' in kwargs:
            shelf_objects = ShelfObject.objects.filter(
                shelf__furniture__labroom__laboratory__pk=kwargs.get('lab_pk'))
        else:
            shelf_objects = ShelfObject.objects.all()
    else:
        shelf_objects = ShelfObject.objects.filter(pk=var)

    shelf_objects = get_limited_shelf_objects(shelf_objects)

    template = get_template('pdf/shelf_object_pdf.html')

    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        return django_excel.make_response_from_array(
            make_book_limited_reached(shelf_objects),
            fileformat,
            file_name="Laboratories.%s" % (fileformat, ))

    context = {
        'object_list': shelf_objects,
        'datetime': timezone.now(),
        'request': request,
        'laboratory': kwargs.get('lab_pk')
    }

    html = template.render(context=context).encode("UTF-8")

    page = HTML(string=html, encoding='utf-8').write_pdf()

    response = HttpResponse(page, content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="report_limited_shelf_objects.pdf"'
    return response
Beispiel #13
0
def report_limited_shelf_objects(request, *args, **kwargs):
    def get_limited_shelf_objects(query):
        for shelf_object in query:
            if shelf_object.limit_reached:
                yield shelf_object

    var = request.GET.get('pk')
    if var is None:
        if 'lab_pk' in kwargs:
            shelf_objects = ShelfObject.objects.filter(
                shelf__furniture__labroom__laboratory__pk=kwargs.get('lab_pk'))
        else:
            shelf_objects = ShelfObject.objects.all()
    else:
        shelf_objects = ShelfObject.objects.filter(pk=var)

    shelf_objects = get_limited_shelf_objects(shelf_objects)

    template = get_template('pdf/shelf_object_pdf.html')

    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        return django_excel.make_response_from_array(
            make_book_limited_reached(shelf_objects), fileformat, file_name="Laboratories.%s" % (fileformat,))

    context = {
        'object_list': shelf_objects,
        'datetime': timezone.now(),
        'request': request,
        'laboratory': kwargs.get('lab_pk')
    }

    html = template.render(
        context=context).encode("UTF-8")

    page = HTML(string=html, encoding='utf-8').write_pdf()

    response = HttpResponse(page, content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="report_limited_shelf_objects.pdf"'
    return response
Beispiel #14
0
def report_h_code(request, *args, **kwargs):
    form = H_CodeForm(request.GET)
    q = []
    if form.is_valid():
        q = form.cleaned_data['hcode']
    fileformat = request.GET.get('format', 'pdf')
    if fileformat in ['xls', 'xlsx', 'ods']:
        object_list = filter_by_user_and_hcode(
            request.user, q, function='convert_hcodereport_list')
        return django_excel.make_response_from_array(
            object_list,
            fileformat,
            file_name="hcode_report.%s" % (fileformat, ))
    else:
        object_list = filter_by_user_and_hcode(
            request.user, q, function='convert_hcodereport_table')

    template = get_template('pdf/hcode_pdf.html')

    context = {
        'verbose_name': "H code report",
        'object_list': object_list,
        'datetime': timezone.now(),
        'request': request,
    }

    html = template.render(context=context)

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="hcode_report.pdf"'
    pisaStatus = pisa.CreatePDF(html,
                                dest=response,
                                link_callback=link_callback,
                                encoding='utf-8')
    if pisaStatus.err:
        return HttpResponse('We had some errors with code %s <pre>%s</pre>' %
                            (pisaStatus.err, html))
    return response
Beispiel #15
0
def export_operations(request, atype):
    if atype == 'data':
        data = [[1, 2, 3], [4, 5, 6]]
        sheet = excel.pe.Sheet(data)
        return excel.make_response(sheet, 'xlsx')
    elif atype == "sheet2":
        return excel.make_response_from_a_table(Operation,
                                                'xlsx',
                                                file_name='sheet2')
    elif atype == "sheet":
        query_sets = Operation.objects.all().values_list(
            'operation_date', 'label', 'debit_or_credit', 'account', 'amount',
            'vat_rate', 'provision_rate', 'all_tax_included', 'apply_vat',
            'apply_provision')
        column_names = [
            'operation_date',
            'label',
            'debit_or_credit',
            'account',
            'amount',
            'vat_rate',
            'vat_amount',
            'provision_rate',
            'provision_amount',
            'all_tax_included',
            'apply_vat',
            'apply_provision',
        ]
        return excel.make_response_from_array(query_sets,
                                              'xlsx',
                                              file_name='sheet')
#        return excel.make_response_from_a_table(
#            Operation, 'xlsx', file_name="sheet")
    else:
        return HttpResponseBadRequest(
            "Bad request. please put one of these " +
            "in your url suffix: sheet, book or custom")
Beispiel #16
0
def sony(request):

    if request.method == "POST":

        try:
            storage = messages.get_messages(request)
            for message in storage:
                print message
            storage.used = True
        except:
            pass

    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        try:
            filehandle = request.FILES['file']
            xls = pd.ExcelFile(filehandle)
            df = xls.parse('Sheet1')
            par = xls.parse('Sheet2').values.transpose()
            df = process_sony(df, par)
        except Exception as e:
            print e
            messages.warning(request,
                             'The uploaded file has some problems: ' + str(e))
            return render(request, 'scanner/sony.html', {
                'form': form,
            })
        return excel.make_response_from_array(
            [df.columns.values.tolist()] + df.as_matrix().tolist(),
            "xls",
            file_name="download",
        )
    else:
        form = UploadFileForm()
    return render(request, 'scanner/sony.html', {
        'form': form,
    })
Beispiel #17
0
def download_as_attachment(request, file_type, file_name):
    return excel.make_response_from_array(data, file_type, file_name=file_name)
Beispiel #18
0
 def get_ods(self, request, *args, **kwargs):
     self.object_list = self.get_queryset()
     context = self.get_context_data()
     file_format = 'ods'
     return django_excel.make_response_from_array(
         self.get_book(context), file_format, file_name="%s.ods" % self.get_file_name(request))
Beispiel #19
0
def export(request, *args, **kwargs):
    """ The view gotten when trying to export grades to .xls format.
    :param request: The HTML request
    :param args: Not used
    :param kwargs: The parameters
    :return: The excel file
    """
    user = request.user

    if not Test.objects.filter(
            module_part__module_edition__coordinators__user=user,
            id=kwargs['pk']):
        raise PermissionDenied()

    test = Test.objects.get(id=kwargs['pk'])

    # Gather all students who have done the test.
    # This dictionary is ordered by the university ID and the date their grade has been added.
    dicts = Studying.objects \
        .prefetch_related('person', 'person__Submitter') \
        .values('person__name', 'person__university_number') \
        .filter(module_edition__modulepart__test=test) \
        .order_by('person__name')

    grades = Grade.objects \
        .filter(test=test) \
        .order_by('time')

    study = Study.objects \
        .get(modules__moduleedition__modulepart__test=test)

    mod_ed = test.module_part.module_edition

    # Set up the first part of the table.
    table = [[
        'Cursus', '{}'.format(mod_ed.module_code), '', '', 'Tijdstip', 'N/A'
    ], ['Collegejaar', '{}'.format(mod_ed.year)],
             ['Toets', '{}'.format(test.name)],
             ['Blok', '{}'.format(mod_ed.block), '', 'Resultaatschaal', ''],
             ['Gelegenheid', ''], [''],
             [
                 'Studentnummer', 'Naam', 'Toetsdatum', 'Resultaat',
                 'Afwijkende categorie', 'Geldigheidsduur'
             ]]

    temp_dict = OrderedDict()
    grade_dict = dict()

    # Set up the second part of the table.
    for grade in grades:
        grade_dict[grade.student.university_number] = grade.grade

    for d in dicts:
        temp_dict[d['person__university_number'][1:]] = d['person__name']

    for u_num, name in temp_dict.items():
        if ('s' + u_num) in grade_dict.keys():
            table.append([
                '{}'.format(u_num), '{}'.format(name), 'N/A',
                '{}'.format(grade_dict['s' + u_num]), 'N/A', 'N/A'
            ])
        else:  # University Number, Student name, Date, Grade, Category, Validity period
            table.append([
                '{}'.format(u_num), '{}'.format(name), 'N/A', 'NVD', 'N/A',
                'N/A'
            ])

    # Return the excel file.
    return excel.make_response_from_array(
        table,
        file_name='{} MODxx {} {}.xlsx'.format(study.abbreviation,
                                               mod_ed.module_code, test.name),
        file_type='xlsx')
Beispiel #20
0
def export_qs_to_file(request,
                      qs,
                      column_names=None,
                      file_type='xlsx',
                      file_name=None,
                      url_name=None,
                      get_params=None,
                      url_arg=None):
    """
    Export query to file.

    :param request:
    :param qs:
    :param column_names:
    :param file_type:
    :param file_name:
    :param url_name:
    :param get_params:
    :param url_arg:
    :return:
    """

    # columns names - go into file
    # fields - extract from db

    column_names = list(column_names)

    # construct file name if it's not given
    if file_name is None:
        file_name = '{}_list_{}.{}'.format(qs.model._meta.model_name,
                                           datetime.datetime.now().isoformat(),
                                           file_type)

    # split fields into fk, m2m, others
    fields = [
        f.name for f in qs.model._meta.local_fields
        if f.__class__.__name__ not in ('ManyToOneRel', 'ForeignKey')
    ]
    fields_fk = [
        f.name for f in qs.model._meta.local_fields
        if f.__class__.__name__ == 'ForeignKey'
    ]
    fields_m2m = [f.name for f in qs.model._meta.many_to_many]

    fields_rtf = [
        f.name for f in qs.model._meta.local_fields
        if f.__class__.__name__ == 'RichTextField'
    ]

    # if custom column names
    if column_names is not None:
        fields_fk = set(column_names) & set(fields_fk)
        fields_m2m = set(column_names) & set(fields_m2m)
        fields = list(set(column_names) - fields_fk - fields_m2m)
    else:
        column_names = fields + list(fields_fk) + list(fields_m2m)

    if url_name is not None:
        column_names.append('link')

    if 'pk' not in fields:
        fields.append('pk')

    if url_arg:
        fields.append(url_arg)

    # get data from local fields (not fk or m2m)
    data = qs.values(*fields)

    get_params = get_params(request) if callable(get_params) else get_params
    get_params = '?{}'.format(get_params) if get_params else ''

    for item in data:

        # add link to concrete object to each row if needed
        if url_name is not None:
            item['link'] = construct_full_url(
                request,
                reverse(url_name,
                        args=[item[url_arg] if url_arg else item['pk']
                              ])) + get_params

        # hit db only if these fields are present
        if fields_fk or fields_m2m:
            obj = qs.model.objects.get(pk=item['pk'])
            # get __str__ for fk
            for fk_field in fields_fk:
                item[fk_field] = str(getattr(obj, fk_field))
            # get list of __str__ for each object in m2m
            for m2m_field in fields_m2m:
                item[m2m_field] = ', '.join(
                    [str(i) for i in getattr(obj, m2m_field).all()])
        # clean ReachTextField value from html tags
        for rtf_field in fields_rtf:
            item[rtf_field] = clean_html_tags(item[rtf_field])

    # convert to array
    array_header = list(
        [cap_words(re.sub(r'_+', ' ', i)) for i in column_names])
    array_data = [[row[field_name] for field_name in column_names]
                  for row in data]
    array = [array_header] + array_data

    return excel.make_response_from_array(array,
                                          file_type,
                                          status=200,
                                          file_name=file_name,
                                          sheet_name='book')
Beispiel #21
0
def download_as_attachment(request, file_type, file_name):
    return excel.make_response_from_array(
        data, file_type, file_name=file_name)
Beispiel #22
0
def download_wide_table(request, nl_mapping_id):
    """ Download wide table. """
    all_fields = WideTable.list_display
    concerned_fields = [e for e in all_fields if e not in ('label', )]

    # native fields are ones of Ebom class
    is_native = []
    header = []
    ebom_fields = dict([
        (e.name, e.verbose_name if hasattr(e, 'verbose_name') else e.name)
        for e in models.Ebom._meta.get_fields()
    ])

    for field in concerned_fields:
        if not hasattr(WideTable, field):
            if field in ebom_fields:
                is_native.append(True)
                header.append(ebom_fields[field])
        else:
            _method = getattr(WideTable, field)

            if field[0:4] == 'get_' and callable(_method):
                is_native.append(False)
                header.append(_method.short_description)

    assert len(concerned_fields) == len(is_native)

    # initialize a wide table object
    wide_table_object = WideTable(models.Ebom, wide_table_dummy_param)

    # export two-dimensional array
    wide_table_matrix = [header]
    ebom_objects = models.Ebom.objects.filter(label__id=nl_mapping_id)

    for ebom_object in ebom_objects:
        # a row for wide table
        wide_table_row = []
        index = 0

        for field in concerned_fields:
            if is_native[index]:
                field_or_fk = getattr(ebom_object, field)

                if isinstance(field_or_fk, Model):
                    wide_table_row.append(str(field_or_fk))
                else:
                    wide_table_row.append(field_or_fk)

            else:
                method = getattr(wide_table_object, field)
                wide_table_row.append(method(ebom_object))

            index += 1

        wide_table_matrix.append(wide_table_row)

    # download file name
    label = models.NominalLabelMapping.objects.get(pk=nl_mapping_id)

    return django_excel.make_response_from_array(wide_table_matrix,
                                                 'xls',
                                                 file_name=str(label))