@vveyss

Как объеденить одинаковые ячейки в столбце при помощи python xlwt?

Имеется следующая функция по формированию excel файла:

def export_excel(request):

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = ("attachment; filename=Numbers_" + str(datetime.datetime.now().strftime("%d/%m/%y")) + '.xls')
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Numbers', cell_overwrite_ok=True)
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    columns = ['Подразделение',
               'Номер',
               'Сумма',
               'Итог (Сумма+ндс+абон.плата)',
               'Итог по подразделению']

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()
    rows = ReportFilter(request.GET,
                        queryset=Parser.objects.all().values_list(
                            'attachment__attachment',
                            'number',
                            'pay',
                            'result')).qs

    rows1 = Numbers.objects.filter(is_enabled=True).values_list('attachment__attachment', 'number')

    temp = []
    for item1 in rows:
        temp.append(item1)
    for item2 in rows1:
        if Parser.objects.filter(number=item2[1]):
            None
        else:
            item2 = list(item2)
            item2.append(250)
            item2.append(250)
            item2 = tuple(item2)
            temp.append(item2)
    temp.sort()
    temp = tuple(temp)

    res = pandas.DataFrame(
        ReportFilter(request.GET, queryset=Parser.objects.annotate().values_list('result')).qs).to_numpy()
    res_sum = res.sum()
    itog = float(res_sum)

    for row in temp:
        row_num += 1

        if row_num == row_num + 1:
            print('MERGE')

        for col_num in range(len(row)):

            if isinstance(row[col_num], datetime.datetime):
                date_time = row[col_num].astimezone(datetime.timezone(datetime.timedelta(hours=7))).strftime('%d/%m/%Y')
                ws.write(row_num, col_num, date_time, font_style)
                ws.write_merge(1, row_num, 0, 0, f'{str(row[0])}')

            else:
                ws.write(row_num, col_num, row[col_num], font_style)
                ws.write(row_num + 1, 1, 'Итог:')
                ws.write(row_num + 1, 2, itog)

    wb.save(response)
    return response

Эта функция формирует отчет следующего вида:

65c33a318be6d743449275.png
Помогите привести к такому виду:

65c33ae9007ba401974717.png
  • Вопрос задан
  • 81 просмотр
Решения вопроса 1
@vveyss Автор вопроса
Так ничего и не вышло у меня с библиотекой xlwt.
Пришлось использовать библиотеку openpyxl.
Код рабочий, только не стал объединять ячейки из последнего столбца.
Может кому-нибудь пригодится.
def export_excel(request):

    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = ("attachment; filename=Numbers_" + str(datetime.datetime.now().strftime("%d/%m/%y")) + '.xlsx')
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    headers = ('Подразделение',
               'Номер',
               'Сумма',
               'Итог (Сумма+ндс+абон.плата)',
               'Итог по подразделению')

    rows_parser = ReportFilter(request.GET, queryset=Parser.objects.all().values_list(
        'attachment__attachment', 'number', 'pay', 'result'
    )).qs
    rows_numbers = ReportFilterNumbers(request.GET, queryset=Numbers.objects.filter(is_enabled=True).values_list(
        'attachment__attachment', 'number'
    )).qs

    res = 0
    temp = []
    subFee = float(str(SubscriptionFee.objects.get(pk=1)))

    for item1 in rows_parser:
        temp.append(item1)
        res += item1[3]

    for item2 in rows_numbers:
        if Parser.objects.filter(number=item2[1]):
            None
        else:
            if Numbers.objects.filter(number=item2[1], cf=True):
                item2 = list(item2)
                item2.extend([0, 0])
                res += item2[3]
                item2 = tuple(item2)
                temp.append(item2)
            else:
                item2 = list(item2)
                item2.extend([subFee, subFee])
                res += item2[3]
                item2 = tuple(item2)
                temp.append(item2)

    temp.sort()

    itog = 0
    for row in range(len(temp)):
        itog += temp[row][3]

    temp.insert(0, headers)
    temp = tuple(temp)

    current_value = temp[1][0]
    start_row_index = 1
    now3 = 0
    sheet.append(headers)

    for row_index in range(1, len(temp)):
        cell_value = temp[row_index][0]
        if cell_value != current_value:
            sheet.append(temp[row_index])
            sheet.cell(row=row_index, column=5).value = now3
            now3 = temp[row_index][3]
            start_row_index = row_index
            current_value = cell_value

        elif cell_value == current_value:
            now3 += temp[row_index][3]
            sheet.append(temp[row_index])
            sheet.merge_cells(start_row=start_row_index + 1, start_column=1, end_row=row_index + 1, end_column=1)
            start_row_index = row_index
            current_value = cell_value

    sheet.cell(row=row_index + 1, column=5).value = now3
    sheet.cell(row=row_index + 2, column=3).value = 'ОБЩИЙ ИТОГ:'
    sheet.cell(row=row_index + 2, column=4).value = itog
    workbook.save(response)
    
    return response
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы