コード例 #1
0
def get_result_data_file(request):
    target = get_object_or_404(Result, pk=request.GET['id'])
    task = get_object_or_404(Task, pk=request.GET['id'])
    if target.application.user != request.user:
        return render(request, '404.html')

    id = int(request.GET['id'])
    type = request.GET['type']

    prefix = get_result_data_dir(id)

    if type == 'sample':
        response = HttpResponse(FileWrapper(file(prefix + '_' + type)),
                                content_type='text/plain')
        response.__setitem__(
            'Content-Disposition',
            'attachment; filename=result_' + str(id) + '.sample')
        return response
    elif type == 'raw':
        response = HttpResponse(FileWrapper(file(prefix + '_' + type)),
                                content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename=result_' + str(
            id) + '.raw'
        return response
    elif type == 'new_conf':
        response = HttpResponse(FileWrapper(file(prefix + '_' + type)),
                                content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename=result_' + str(
            id) + '_new_conf'
        return response
コード例 #2
0
    def generate_report(information_json, show_concepts=True):

        PhysicalFinancialAdvanceReport.show_concepts = show_concepts

        output = StringIO.StringIO()

        # Create an new Excel file and add a worksheet.
        # workbook = Workbook('report.xlsx')
        workbook = Workbook(output)
        worksheet_1 = workbook.add_worksheet('Programado')
        worksheet_2 = workbook.add_worksheet('Avance Físico Financiero')

        # Widen the first column to make the text clearer.
        worksheet_1.set_column('A:H', 20)

        # Add a bold format to use to highlight cells.
        bold = workbook.add_format({'bold': True})

        # Write some simple text.
        worksheet_1.write('A1', 'Programa Licitación', bold)

        PhysicalFinancialAdvanceReport.add_programmed_table(workbook, worksheet_1, information_json)
        PhysicalFinancialAdvanceReport.add_progress_table(workbook, worksheet_2, information_json)

        workbook.close()

        response = StreamingHttpResponse(FileWrapper(output),
                                         content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

        response['Content-Disposition'] = 'attachment; filename=Avance_Fisico_Financiero.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #3
0
    def generate_report(information_json, show_concepts=True):

        if len(information_json) == 0:
            output = StringIO.StringIO()
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Avance Financiero Interno')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:A', 20)
            worksheet.write('A1',
                            'Aún no se ha agregado el catálogo de conceptos.')
        else:

            FinancialAdvanceReport.show_concepts = show_concepts

            output = StringIO.StringIO()

            # Create an new Excel file and add a worksheet.
            # workbook = Workbook('report.xlsx')
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Avance Financiero Interno')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:H', 20)

            # Add a bold format to use to highlight cells.
            bold = workbook.add_format({'bold': True})

            # Write some simple text.
            worksheet.write('A1', 'Avance Financiero Interno', bold)

            FinancialAdvanceReport.add_headers(workbook, worksheet)

            FinancialAdvanceReport.add_concepts(workbook, worksheet,
                                                information_json['line_items'])

            # Insert an image.
            # worksheet.insert_image('B5', 'logo.png')

        workbook.close()
        response = StreamingHttpResponse(
            FileWrapper(output),
            content_type=
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

        response[
            'Content-Disposition'] = 'attachment; filename=Reporte_Avance_Financiero.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #4
0
ファイル: views.py プロジェクト: jadolg/SubsCafe
def download(request, id):
    subtitulo = Subtitulo.objects.get(id=id)
    subtitulo.descargas += 1
    subtitulo.save()
    response = HttpResponse(FileWrapper(
        open(STASH_FOLDER + subtitulo.ahash, 'rb')),
                            content_type='text/plain')
    nombre = '"' + os.path.splitext(
        subtitulo.nombre)[0] + " - [subscafe.gntk.snet]" + os.path.splitext(
            subtitulo.nombre)[1] + '"'

    response['Content-Disposition'] = 'attachment; filename=' + nombre + ';'
    return response
コード例 #5
0
def Download_File(request, id):

    mfile = libarary.objects.get(file_id=id)

    path = os.path.abspath(mfile.file.url)
    print path
    wrapper = FileWrapper(file(path))
    response = HttpResponse(wrapper, content_type='text/plain')
    response[
        'Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(
            path)
    response['Content-Length'] = os.path.getsize(path)

    return response
コード例 #6
0
    def generate_report(information_json, show_concepts=True):

        if len(information_json) == 0:
            output = StringIO.StringIO()
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Avance Financiero Interno')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:A', 20)
            worksheet.write('A1',
                            'Aún no se ha agregado el catálogo de conceptos.')
        else:
            EstimateReports.show_concepts = show_concepts

            output = StringIO.StringIO()

            # Create an new Excel file and add a worksheet.
            workbook = Workbook(output)
            numberSheet = 1
            for info in information_json:
                worksheet = workbook.add_worksheet('Hoja de Estimación ' +
                                                   str(numberSheet))
                numberSheet += 1

                # Widen the first column to make the text clearer.
                worksheet.set_column('A:E', 20)
                worksheet.set_column('F:F', 2)
                worksheet.set_column('G:K', 20)

                EstimateReports.add_headers(workbook, worksheet, info)

            #EstimateReports.add_concepts(workbook, worksheet, information_json)

            # Insert an image.
            # worksheet.insert_image('B5', 'logo.png')

        workbook.close()
        response = StreamingHttpResponse(
            FileWrapper(output),
            content_type=
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

        response[
            'Content-Disposition'] = 'attachment; filename=hoja de estimación.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #7
0
    def generate_report(information_json, ):
        if len(information_json) == 0:
            output = StringIO.StringIO()
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Estimaciones por Contratista')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:A', 20)
            worksheet.write(
                'A1',
                'Aún no se ha generado información suficiente para generar el reporte.'
            )
        else:

            output = StringIO.StringIO()

            # Create an new Excel file and add a worksheet.
            workbook = Workbook(output)

            # Iterate through the contractors array.
            print information_json
            for contractor in information_json['data']:
                worksheet = workbook.add_worksheet(
                    contractor['contractor_name'])
                EstimateReportsForContractors.add_headers(
                    workbook, worksheet, information_json, contractor)
                EstimateReportsForContractors.add_estimates_table(
                    workbook, worksheet, contractor['estimates'])

        workbook.close()
        response = StreamingHttpResponse(
            FileWrapper(output),
            content_type=
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

        response[
            'Content-Disposition'] = 'attachment; filename=Estimaciones_de_los_Contratistas.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #8
0
ファイル: accounts_list.py プロジェクト: agsneutron/salcedo
    def generate_accounts_list(accounts_array):

        if len(accounts_array) == 0:
            output = StringIO.StringIO()
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Cuentas Contables')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:A', 20)
            worksheet.write(
                'A1',
                'No se encontraron registros para la búsqueda de cuentas contables.'
            )
        else:

            output = StringIO.StringIO()

            # Create an new Excel file and add a worksheet.
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Lista Nominal')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:J', 15)
            worksheet.set_column('A:K', 25)

            AccountsListFile.add_headers(workbook, worksheet, accounts_array)

        workbook.close()
        response = StreamingHttpResponse(
            FileWrapper(output),
            content_type=
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

        response[
            'Content-Disposition'] = 'attachment; filename=Cuentas_Contables.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #9
0
    def generate_report(data_set):

        if len(data_set) == 0:
            output = StringIO.StringIO()
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet(
                'Totales por Percepciones y Deducciones')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:A', 20)
            worksheet.write('A1', 'No se encontraron registros.')
        else:

            output = StringIO.StringIO()

            # Create an new Excel file and add a worksheet.
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Totales')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:D', 20)

            EarningsDeductionsTotalEarnings.add_headers(
                workbook, worksheet, data_set)

        workbook.close()
        response = StreamingHttpResponse(
            FileWrapper(output),
            content_type=
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

        response[
            'Content-Disposition'] = 'attachment; filename=Totales_por_percepciones_y_deducciones.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #10
0
    def generate_payroll_list(payroll_array):

        if len(payroll_array) == 0:
            output = StringIO.StringIO()
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Lista Nominal')

            # Widen the first column to make the text clearer.
            worksheet.set_column('A:A', 20)
            worksheet.write('A1', 'No se encontraron registros para el periodo nominal seleccionado.')
        else:

            output = StringIO.StringIO()

            # Create an new Excel file and add a worksheet.
            workbook = Workbook(output)
            worksheet = workbook.add_worksheet('Lista Nominal')


            # Widen the first column to make the text clearer.
            worksheet.set_column('A:K', 15)


            PayrollListFile.add_headers(workbook, worksheet, payroll_array)



        workbook.close()
        response = StreamingHttpResponse(FileWrapper(output),
                                         content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

        response['Content-Disposition'] = 'attachment; filename=Listado_Nominal.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #11
0
ファイル: trial_balance.py プロジェクト: agsneutron/salcedo
    def generate_report(general_data, policies_details_set):
        """
        Entry point to generate the trial report.

        :param general_data: General Data for the report, such as Fiscal Period, Year, etc.
        :param policies_details_set: Set of policy details to be processed.
        :return: HttpResponse containing the downloadable file.
        """

        output = StringIO.StringIO()
        workbook = Workbook(output)
        worksheet = workbook.add_worksheet('Balanza de Comprobación')

        if len(policies_details_set) == 0:
            # Widen the first column to make the text clearer.
            #worksheet.write('A1', 'No se encontraron datos pertenecientes al periodo.')
            pass

        else:
            TrialBalanceReport.add_headers(workbook, worksheet, general_data)
            TrialBalanceReport.add_policies_details(workbook, worksheet,
                                                    policies_details_set)

        workbook.close()
        response = StreamingHttpResponse(
            FileWrapper(output),
            content_type=
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

        response[
            'Content-Disposition'] = 'attachment; filename=Balanza_de_Comprobación.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #12
0
    def generate_report(self, data):
        #data = self.get_test_data()

        output = StringIO.StringIO()

        # Create an new Excel file and add a worksheet.
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet()

        # Get all the formats
        formats = self.get_formats(workbook)

        offset = 0  # Horizontal offset
        header_start_row = 1  # Everything else should be dynamic
        start_row = header_start_row + 6  # Everything else should be dynamic
        current_row = start_row  # Everything else should be dynamic
        active_column_width = 30
        passive_column_width = 30

        '''
            Header section
        '''
        # Insert Logo
        worksheet.insert_image(header_start_row, offset,
                               os.path.dirname(os.path.abspath(__file__)) + '/assets/images/salcedo.png',
                               {
                                   'x_offset': 50,
                                   'y_offset': 0
                               })

        worksheet.merge_range(header_start_row + 2, 2 + offset, header_start_row + 2, 5 + offset,
                              'Salcedo Construcción y Supervision SA de CV', formats['report_header'])
        worksheet.merge_range(header_start_row + 3, 2 + offset, header_start_row + 3, 5 + offset,
                              'Movimientos de Cuenta', formats['report_header'])

        date_label = time.strftime("%d de %B de %Y")

        # Widths
        label_column_width = 30
        value_column_width = 20

        worksheet.set_column(offset + 0, offset + 2, 5)  # Number
        worksheet.set_column(offset + 1, offset + 3, 26)  # Description
        worksheet.set_column(offset + 2, offset + 4, 13)  # Debit
        worksheet.set_column(offset + 3, offset + 5, 13)  # Credit
        worksheet.set_column(offset + 4, offset + 6, 12)  # Policy Folio
        worksheet.set_column(offset + 5, offset + 7, 25)  # Policy Type

        '''
            General info
        '''

        # Account Number
        worksheet.merge_range(current_row, offset, current_row, 1 + offset,
                              "Número de Cuenta", formats['info_label'])

        worksheet.write(current_row, 2 + offset, data['account_number'], formats['number_1'])

        # Account Name
        worksheet.merge_range(current_row, 3 + offset, current_row, 4 + offset,
                              "Nombre de Cuenta", formats['info_label'])
        worksheet.write(current_row, 5 + offset, data['account_name'], formats['number_1'])

        current_row += 1

        # Grouping Code
        worksheet.merge_range(current_row, offset, current_row, 1 + offset,
                              "Código Agrupador", formats['info_label'])
        worksheet.write(current_row, 2 + offset, data['grouping_code'], formats['number_1'])

        # Grouping Code Name
        worksheet.merge_range(current_row, 3 + offset, current_row, 4 + offset,
                              "Tipo de Cuenta", formats['info_label'])

        worksheet.write(current_row, 5 + offset, data['grouping_code_name'], formats['number_1'])

        current_row += 1

        # Parent Account Number
        worksheet.merge_range(current_row, offset, current_row, 1 + offset,
                              "Número de Cuenta Padre", formats['info_label'])
        worksheet.write(current_row, 2 + offset, data['parent_account_number'], formats['number_1'])

        # Parent Account Name
        worksheet.merge_range(current_row, 3 + offset, current_row, 4 + offset,
                              "Nombre de la Cuenta Padre", formats['info_label'])
        worksheet.write(current_row, 5 + offset, data['parent_account_name'], formats['number_1'])

        current_row += 1

        # Fiscal Period Month
        worksheet.merge_range(current_row, offset, current_row, 1 + offset,
                              "Mes Fiscal", formats['info_label'])
        worksheet.write(current_row, 2 + offset, data['fiscal_period_month'], formats['number_1'])
        # Fiscal Period Year
        worksheet.merge_range(current_row, 3 + offset, current_row, 4 + offset,
                              "Año Fiscal", formats['info_label'])

        worksheet.write(current_row, 5 + offset, data['fiscal_period_year'], formats['number_1'])

        '''
            Transactions Section
        '''

        current_row += 2
        worksheet.write(current_row, 4 + offset, "Total Debe", formats['report_header'])
        worksheet.write(current_row, 5 + offset, data['total_debit'], formats['currency_1'])
        current_row += 1
        worksheet.write(current_row, 4 + offset, "Total Haber", formats['report_header'])
        worksheet.write(current_row, 5 + offset, data['total_credit'], formats['currency_1'])

        current_row += 1
        # Headers
        worksheet.write(current_row, offset, '#', formats['info_label'])
        worksheet.write(current_row, 1 + offset, 'Descripción', formats['info_label'])
        worksheet.write(current_row, 2 + offset, 'Debe', formats['info_label'])
        worksheet.write(current_row, 3 + offset, 'Haber', formats['info_label'])
        worksheet.write(current_row, 4 + offset, 'Póliza', formats['info_label'])
        worksheet.write(current_row, 5 + offset, 'Tipo de Póliza', formats['info_label'])

        current_row += 1
        for idx, transaction in enumerate(data['transactions']):
            worksheet.write(current_row, offset, idx + 1, formats['light_label'])
            worksheet.write(current_row, 1 + offset, transaction['description'], formats['data_1'])
            worksheet.write(current_row, 2 + offset, transaction['debit'], formats['currency_1'])
            worksheet.write(current_row, 3 + offset, transaction['credit'], formats['currency_1'])
            worksheet.write(current_row, 4 + offset, transaction['policy_folio'], formats['data_1'])
            worksheet.write(current_row, 5 + offset, transaction['policy_type'], formats['data_1'])

            current_row += 1

        workbook.close()

        response = StreamingHttpResponse(FileWrapper(output),
                                         content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

        response['Content-Disposition'] = 'attachment; filename=' + data['report_title'] + '.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #13
0
ファイル: views.py プロジェクト: vbuilvicente/slack-clone
def get_file(request, slug):
    fileExt = (
        (u'text', u'.txt'),
        (u'applescript', u'.scpt'),
        (u'boxnote', u'.bn'),  # este
        (u'c', u'.c'),
        (u'csharp', u'.cs'),
        (u'cpp', u'.cpp'),
        (u'css', u'.css'),
        (u'csv', u'.csv'),
        (u'clojure', u'.clj'),
        (u'coffeescript', u'.coffee'),
        (u'cfm', u'.cf'),
        (u'crystal', u'.csp'),
        (u'cypher', u'cy'),
        (u'd', u'.d'),
        (u'dart', u'.dart'),
        (u'diff', u'.diff'),
        (u'dockerfile', u'.dockerfile'),
        (u'erlang', u'.hrl'),
        (u'fsharp', u'.fs'),
        (u'fortran', u'.f'),
        (u'gherkin', u'Gherkin'),  # este
        (u'go', u'.go'),
        (u'groovy', u'.groovy'),
        (u'html', u'.html'),
        (u'handlebars', u'.hbs'),
        (u'haskell', u'.hs'),
        (u'haxe', u'.hx'),
        (u'java', u'.java'),
        (u'javascript', u'.js'),
        (u'julia', u'.jl'),
        (u'kotlin', u'.kt'),
        (u'latex', u'.dtx'),
        (u'lisp', u'.lsp'),
        (u'lua', u'.lua'),
        (u'matlab', u'.m'),
        (u'mumps', u'.m'),  # a
        (u'markdown', u'.md'),
        (u'ocaml', u'.ml'),
        (u'objc', u'.mm'),
        (u'php', u'.php'),
        (u'pascal', u'.dpr'),
        (u'perl', u'.pl'),
        (u'pig', u'.pig'),
        (u'post', u'Post'),
        (u'powershell', u'.ps1'),
        (u'puppet', u'.pp'),
        (u'python', u'.py'),
        (u'r', u'.r'),
        (u'ruby', u'.rb'),
        (u'rust', u'.rs'),
        (u'sql', u'.sql'),
        (u'sass', u'.sass'),
        (u'scala', u'.scala'),
        (u'scheme', u'.ss'),
        (u'shell', u'.ksh'),
        (u'smalltalk', u'Smalltalk'),  # este
        (u'swift', u'.swift'),
        (u'tsv', u'.tsv'),
        (u'vb', u'.vb'),
        (u'vbscript', u'.vbscript'),
        (u'velocity', u'.vtl'),
        (u'verilog', u'.bsv'),
        (u'xml', u'.xml'),
        (u'yaml', u'.yaml'),
    )

    item = get_object_or_404(SlackFile, slug=slug)
    ext = dict(fileExt)
    if item is not None:
        if isinstance(item, Snippet):
            try:
                name = item.title + ext[item.type]
                temp = tempfile.TemporaryFile()
                temp.write(item.code)
                temp.flush()
                temp.seek(0)
                wrapper = FileWrapper(temp)
            except Exception as e:
                print(e)
        elif isinstance(item, FilesUp):
            wrapper = FileWrapper(file(SITE_ROOT + item.file_up.url))
            name = item.title + "." + item.extension
        elif isinstance(item, ImageUp):
            wrapper = FileWrapper(file(SITE_ROOT + item.image_up.url))
            name = item.title + "." + item.extension
        elif isinstance(item, Post):
            try:
                name = item.title + ".txt"
                temp = tempfile.TemporaryFile()
                temp.write(item.code)
                temp.flush()
                temp.seek(0)
                wrapper = FileWrapper(temp)
            except Exception as e:
                print(e)

        response = HttpResponse(wrapper, content_type='application/force-download')
        response['Content-Disposition'] = 'attachment; filename=\"' + name + '\"'
        return response
コード例 #14
0
ファイル: general_balance.py プロジェクト: agsneutron/salcedo
    def generate_excel_document(self, info):
        # Get Grouping Code Objects
        short_term_active = GroupingCode.objects.get(grouping_code=Decimal("100.01"))
        long_term_active = GroupingCode.objects.get(grouping_code=Decimal("100.02"))

        short_term_passive = GroupingCode.objects.get(grouping_code=Decimal("200.01"))
        long_term_passive = GroupingCode.objects.get(grouping_code=Decimal("200.02"))

        accounting_capital = GroupingCode.objects.get(grouping_code=Decimal("300.00"))

        output = StringIO.StringIO()
        # Create an new Excel file and add a worksheet.
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet()

        # Get all the formats
        formats = self.get_formats(workbook)

        offset = 1  # Horizontal offset
        header_start_row = 1  # Everything else should be dynamic
        start_row = header_start_row + 6  # Everything else should be dynamic
        current_row = start_row  # Everything else should be dynamic
        active_column_width = 30
        passive_column_width = 30

        # Setup Worksheet
        worksheet.set_portrait()
        worksheet.set_paper(1)
        worksheet.fit_to_pages(1, 1)
        # Left, right, top, bottom
        worksheet.set_margins(0, 0.7, 0.75, 0.75)

        # Header
        # Insert Logo
        worksheet.insert_image(header_start_row, offset,
                               os.path.dirname(os.path.abspath(__file__)) + '/assets/images/salcedo.png',
                               {
                                   'x_offset': 80,
                                   'y_offset': 0
                               })

        worksheet.merge_range(header_start_row + 2, 1 + offset, header_start_row + 2, 4 + offset,
                              'Salcedo Construcción y Supervision SA de CV', formats['report_header'])

        worksheet.merge_range(header_start_row + 3, 1 + offset, header_start_row + 3, 4 + offset,
                              'Balance General al ' + time.strftime("%d de %B de %Y"), formats['report_header'])

        # Add the 'Active' label
        worksheet.set_column(offset, offset, active_column_width)
        worksheet.merge_range(current_row, 0 + offset, current_row, 1 + offset, 'Activo', formats['level_0_header'])

        current_row += 1
        # -- Short Term Actives Section
        # Add label
        short_term_active_label = short_term_active.account_name
        worksheet.merge_range(current_row, 0 + offset, current_row, 1 + offset, short_term_active_label,
                              formats['level_00_header'])
        current_row += 1
        # Add records.
        total_short_term_active = len(info[short_term_active])  # For readability
        short_term_active_total = 0
        for idx, record in enumerate(info[short_term_active]):
            name = record['code'].account_name
            ammount = record['amount']

            worksheet.write(current_row, 0 + offset, name, formats['level_1_label'])
            worksheet.write(current_row, 1 + offset, ammount, formats['currency_1'])

            short_term_active_total += ammount

            current_row += 1

        # Write Totals
        short_term_active_total_row = current_row
        worksheet.write(current_row, 0 + offset, 'Total de ' + short_term_active_label, formats['level_1_total_label'])

        if total_short_term_active > 0:
            cell_value = '=SUM(' + xlsxwriter.utility.xl_col_to_name(
                1 + offset) + '' + str(
                current_row - total_short_term_active + 1) + ':' + xlsxwriter.utility.xl_col_to_name(
                1 + offset) + '' + str(current_row) + ')'
        else:
            cell_value = 0

        worksheet.write(current_row, 1 + offset, cell_value,
                        formats['currency_1'])

        current_row += 2
        # -- Long Term Actives Section
        # Add label
        long_term_active_label = long_term_active.account_name
        worksheet.merge_range(current_row, 0 + offset, current_row, 1 + offset, long_term_active_label,
                              formats['level_00_header'])
        current_row += 1
        # Add records.
        total_long_term_active = len(info[long_term_active])  # For readability
        for idx, record in enumerate(info[long_term_active]):
            name = record['code'].account_name
            ammount = record['amount']

            worksheet.write(current_row, 0 + offset, name, formats['level_1_label'])
            worksheet.write(current_row, 1 + offset, ammount, formats['currency_1'])

            current_row += 1

        # Write Totals
        long_term_active_total_row = current_row
        worksheet.write(current_row, 0 + offset, 'Total de ' + long_term_active_label, formats['level_1_total_label'])

        if total_long_term_active > 0:
            cell_value = '=SUM(' + xlsxwriter.utility.xl_col_to_name(
                1 + offset) + '' + str(
                current_row - total_long_term_active + 1) + ':' + xlsxwriter.utility.xl_col_to_name(
                1 + offset) + '' + str(current_row) + ')'
        else:
            cell_value = 0

        worksheet.write(current_row, 1 + offset, cell_value,
                        formats['currency_1'])

        current_row += 2

        # Absolute Totals
        active_absolute_total_row = current_row
        worksheet.write(current_row, 0 + offset, 'Total de Activo', formats['level_00_total_label'])
        worksheet.write(current_row, 1 + offset, '=SUM(' + xlsxwriter.utility.xl_col_to_name(
            1 + offset) + '' + str(
            short_term_active_total_row + 1) + ',' + xlsxwriter.utility.xl_col_to_name(
            1 + offset) + '' + str(long_term_active_total_row + 1) + ')',
                        formats['currency_2'])

        current_row = start_row

        # Use to write the next sections
        passive_offset = offset + 3

        # Add the 'Passive' label
        worksheet.set_column(passive_offset, passive_offset, passive_column_width)
        worksheet.merge_range(current_row, 0 + passive_offset, current_row, 1 + passive_offset, 'Pasivo',
                              formats['level_0_header'])

        current_row += 1

        # -- Short Term Passives Section
        # Add label
        short_term_passive_label = short_term_passive.account_name
        worksheet.merge_range(current_row, 0 + passive_offset, current_row, 1 + passive_offset,
                              short_term_passive_label,
                              formats['level_00_header'])
        current_row += 1
        # Add records.
        total_short_term_passive = len(info[short_term_passive])  # For readability
        for idx, record in enumerate(info[short_term_passive]):
            name = record['code'].account_name
            ammount = record['amount']

            worksheet.write(current_row, 0 + passive_offset, name, formats['level_1_label'])
            worksheet.write(current_row, 1 + passive_offset, ammount, formats['currency_1'])

            current_row += 1

        # Write Totals
        short_term_passive_total_row = current_row
        worksheet.write(current_row, 0 + passive_offset, 'Total de ' + short_term_passive_label,
                        formats['level_1_total_label'])

        if total_short_term_active > 0:
            cell_value = '=SUM(' + xlsxwriter.utility.xl_col_to_name(
                1 + passive_offset) + '' + str(
                current_row - total_short_term_passive + 1) + ':' + xlsxwriter.utility.xl_col_to_name(
                1 + passive_offset) + '' + str(current_row) + ')'
        else:
            cell_value = 0
        worksheet.write(current_row, 1 + passive_offset, cell_value,
                        formats['currency_1'])
        current_row += 2

        # -- Long Term Pasives Section
        # Add label
        long_term_passive_label = long_term_passive.account_name
        worksheet.merge_range(current_row, 0 + passive_offset, current_row, 1 + passive_offset, long_term_passive_label,
                              formats['level_00_header'])
        current_row += 1
        # Add records.
        total_long_term_passive = len(info[long_term_passive])  # For readability
        for idx, record in enumerate(info[long_term_passive]):
            name = record['code'].account_name
            ammount = record['amount']

            worksheet.write(current_row, 0 + passive_offset, name, formats['level_1_label'])
            worksheet.write(current_row, 1 + passive_offset, ammount, formats['currency_1'])

            current_row += 1

        # Write Totals
        long_term_passive_total_row = current_row
        worksheet.write(current_row, 0 + passive_offset, 'Total de ' + long_term_passive_label,
                        formats['level_1_total_label'])

        if total_long_term_passive > 0:
            cell_value = '=SUM(' + xlsxwriter.utility.xl_col_to_name(
                1 + passive_offset) + '' + str(
                current_row - total_long_term_passive + 1) + ':' + xlsxwriter.utility.xl_col_to_name(
                1 + passive_offset) + '' + str(current_row) + ')'
        else:
            cell_value = 0

        worksheet.write(current_row, 1 + passive_offset, cell_value,
                        formats['currency_1'])

        current_row += 2

        # Absolute Totals
        passive_absolute_total_row = current_row
        worksheet.write(current_row, 0 + passive_offset, 'Total de Passivo', formats['level_00_total_label'])
        worksheet.write(current_row, 1 + passive_offset, '=SUM(' + xlsxwriter.utility.xl_col_to_name(
            1 + passive_offset) + '' + str(
            short_term_passive_total_row + 1) + ',' + xlsxwriter.utility.xl_col_to_name(
            1 + passive_offset) + '' + str(long_term_passive_total_row + 1) + ')',
                        formats['currency_2'])

        current_row += 2

        # -- Accounting Capital Section
        # Add label
        accounting_capital_label = accounting_capital.account_name
        worksheet.merge_range(current_row, 0 + passive_offset, current_row, 1 + passive_offset,
                              accounting_capital_label,
                              formats['level_0_header'])
        current_row += 1
        # Add records.
        total_accounting_capital = len(info[long_term_passive])  # For readability
        for idx, record in enumerate(info[accounting_capital]):
            name = record['code'].account_name
            ammount = record['amount']

            worksheet.write(current_row, 0 + passive_offset, name, formats['level_1_label'])
            worksheet.write(current_row, 1 + passive_offset, ammount, formats['currency_1'])

            current_row += 1

        # Write Totals
        accounting_capital_total_row = current_row
        worksheet.write(current_row, 0 + passive_offset, 'Total de Capital Contable',
                        formats['level_00_total_label'])

        if total_accounting_capital > 0:
            cell_value = '=SUM(' + xlsxwriter.utility.xl_col_to_name(
                1 + passive_offset) + '' + str(
                current_row - total_accounting_capital + 1) + ':' + xlsxwriter.utility.xl_col_to_name(
                1 + passive_offset) + '' + str(current_row) + ')'
        else:
            cell_value = 0
        worksheet.write(current_row, 1 + passive_offset, cell_value,
                        formats['currency_1'])

        current_row += 2

        worksheet.write(current_row, 0 + passive_offset, 'Capital Contable + Pasivo',
                        formats['level_00_total_label'])
        worksheet.write(current_row, 1 + passive_offset, '=SUM(' + xlsxwriter.utility.xl_col_to_name(
            1 + passive_offset) + '' + str(
            passive_absolute_total_row + 1) + ',' + xlsxwriter.utility.xl_col_to_name(
            1 + passive_offset) + '' + str(accounting_capital_total_row + 1) + ')',
                        formats['currency_1'])

        workbook.close()

        response = StreamingHttpResponse(FileWrapper(output),
                                         content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

        response['Content-Disposition'] = 'attachment; filename=Balance_general.xlsx'
        response['Content-Length'] = output.tell()

        output.seek(0)

        return response
コード例 #15
0
def draw_cinemahall(schedule_id):

    url = CINEMA_HALL.format(schedule_id, KINOHOD_API_KEY)

    x_offset = 15
    y_offset = 30
    shift = 10

    # context = ssl._create_unverified_context()

    with contextlib.closing(urllib2.urlopen(url)) as jf:
        html_data = json.loads(jf.read())

    for info in html_data:
        for section in info['sections']:
            picture_width = int(section['width']) + 2 * x_offset
            picture_height = int(section['height']) + y_offset
            data = np.zeros((picture_height, picture_width, 3), dtype=np.uint8)
            data[:, :] = [242, 242, 242]

            low_price, high_price = 0, 0

            for counter, seat in enumerate(section['seats']):
                x, y = (int(seat['x']) + x_offset + shift / 2,
                        int(seat['y']) + y_offset)

                seat_height, seat_width = (int(seat['height']),
                                           int(seat['width']))
                if seat['status'] == 'vacant':
                    if seat['class'] == 'color1':
                        low_price = seat['price']
                        data[y - seat_height / 2:y + seat_height / 2,
                             x - seat_width / 2:x + seat_width / 2] = BLUE
                    if seat['class'] == 'color2':
                        high_price = seat['price']
                        data[y - seat_height / 2:y + seat_height / 2,
                             x - seat_width / 2:x + seat_width / 2] = ORANGE

                else:
                    data[y - seat_height / 2:y + seat_height / 2,
                         x - seat_width / 2:x + seat_width / 2] = LIGHT_GREY

            # draw price icons
            x_base = x_offset + (shift / 2) + 2 * seat_width
            data[picture_height - int(1.25 * seat_height):picture_height -
                 int(.25 * seat_height),
                 x_base - seat_width / 2:x_base + seat_width / 2] = BLUE

            x_base_orange = x_base + 4 * seat_width
            if high_price > low_price:
                data[picture_height - int(1.25 * seat_height):picture_height -
                     int(.25 * seat_height), x_base_orange -
                     seat_width / 2:x_base_orange + seat_width / 2] = ORANGE

            img = Image.fromarray(data)
            draw = ImageDraw.Draw(img)
            draw_seat_numbers(draw, section, x_offset, y_offset)

            # draw price texts
            draw.text(
                (x_base + seat_width, picture_height - int(1. * seat_height)),
                '{} {}'.format(low_price, SIGN_RUB),
                fill=FILL_BLACK)

            if high_price > low_price:
                high_str = '{} {}'.format(high_price, SIGN_RUB)
                draw.text((x_base_orange + seat_width,
                           picture_height - int(1. * seat_height)),
                          high_str,
                          fill=FILL_BLACK)

            draw_window(draw, picture_width, x_offset, y_offset)

    tmpfile = tempfile.TemporaryFile()
    img.save(tmpfile, format='bmp', quality=80)
    tmpfile.seek(0)
    wrapper = FileWrapper(tmpfile)
    return wrapper