Passed
Push — master ( 386fb9...34ec8c )
by Guangyu
17:38 queued 10s
created

excelexporters.combinedequipmentbatch   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 189
Duplicated Lines 90.48 %

Importance

Changes 0
Metric Value
wmc 12
eloc 132
dl 171
loc 189
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
B export() 33 33 5
C generate_excel() 138 138 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import base64
2
import uuid
3
import os
4
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
5
from openpyxl.drawing.image import Image
6
from openpyxl import Workbook
7
8
9
####################################################################################################################
10
# PROCEDURES
11
# Step 1: Validate the report data
12
# Step 2: Generate excelexporters file
13
# Step 3: Encode the excelexporters file to Base64
14
####################################################################################################################
15
16 View Code Duplication
def export(result, space_name, reporting_start_datetime_local, reporting_end_datetime_local):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
17
    ####################################################################################################################
18
    # Step 1: Validate the report data
19
    ####################################################################################################################
20
    if result is None:
21
        return None
22
23
    ####################################################################################################################
24
    # Step 2: Generate excel file from the report data
25
    ####################################################################################################################
26
    filename = generate_excel(result,
27
                              space_name,
28
                              reporting_start_datetime_local,
29
                              reporting_end_datetime_local)
30
    ####################################################################################################################
31
    # Step 3: Encode the excel file to Base64
32
    ####################################################################################################################
33
    try:
34
        with open(filename, 'rb') as binary_file:
35
            binary_file_data = binary_file.read()
36
    except IOError as ex:
37
        pass
38
39
    # Base64 encode the bytes
40
    base64_encoded_data = base64.b64encode(binary_file_data)
0 ignored issues
show
introduced by
The variable binary_file_data does not seem to be defined for all execution paths.
Loading history...
41
    # get the Base64 encoded data using human-readable characters.
42
    base64_message = base64_encoded_data.decode('utf-8')
43
    # delete the file from server
44
    try:
45
        os.remove(filename)
46
    except NotImplementedError as ex:
47
        pass
48
    return base64_message
49
50
51 View Code Duplication
def generate_excel(report, space_name, reporting_start_datetime_local, reporting_end_datetime_local):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
52
53
    wb = Workbook()
54
    ws = wb.active
55
56
    # Row height
57
    ws.row_dimensions[1].height = 102
58
    for i in range(2, 5 + 1):
59
        ws.row_dimensions[i].height = 42
60
61
    for i in range(6, len(report['combined_equipments']) + 15):
62
        ws.row_dimensions[i].height = 60
63
64
    # Col width
65
    ws.column_dimensions['A'].width = 1.5
66
67
    ws.column_dimensions['B'].width = 25.0
68
69
    for i in range(ord('C'), ord('L')):
70
        ws.column_dimensions[chr(i)].width = 15.0
71
72
    # Font
73
    name_font = Font(name='Constantia', size=15, bold=True)
74
    title_font = Font(name='宋体', size=15, bold=True)
75
    data_font = Font(name='Franklin Gothic Book', size=11)
76
77
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
78
    f_border = Border(left=Side(border_style='medium', color='00000000'),
79
                      right=Side(border_style='medium', color='00000000'),
80
                      bottom=Side(border_style='medium', color='00000000'),
81
                      top=Side(border_style='medium', color='00000000')
82
                      )
83
    b_border = Border(
84
        bottom=Side(border_style='medium', color='00000000'),
85
    )
86
87
    b_c_alignment = Alignment(vertical='bottom',
88
                              horizontal='center',
89
                              text_rotation=0,
90
                              wrap_text=True,
91
                              shrink_to_fit=False,
92
                              indent=0)
93
    c_c_alignment = Alignment(vertical='center',
94
                              horizontal='center',
95
                              text_rotation=0,
96
                              wrap_text=True,
97
                              shrink_to_fit=False,
98
                              indent=0)
99
    b_r_alignment = Alignment(vertical='bottom',
100
                              horizontal='right',
101
                              text_rotation=0,
102
                              wrap_text=True,
103
                              shrink_to_fit=False,
104
                              indent=0)
105
    c_r_alignment = Alignment(vertical='bottom',
106
                              horizontal='center',
107
                              text_rotation=0,
108
                              wrap_text=True,
109
                              shrink_to_fit=False,
110
                              indent=0)
111
112
    # Img
113
    img = Image("excelexporters/myems.png")
114
    img.width = img.width * 0.85
115
    img.height = img.height * 0.85
116
    ws.add_image(img, 'B1')
117
118
    # Title
119
    ws.row_dimensions[3].height = 60
120
121
    ws['B3'].font = name_font
122
    ws['B3'].alignment = b_r_alignment
123
    ws['B3'] = '空间:'
124
    ws['C3'].border = b_border
125
    ws['C3'].alignment = b_c_alignment
126
    ws['C3'].font = name_font
127
    ws['C3'] = space_name
128
129
    ws['F3'].font = name_font
130
    ws['F3'].alignment = b_r_alignment
131
    ws['F3'] = '日期:'
132
    ws['G3'].border = b_border
133
    ws['G3'].alignment = b_c_alignment
134
    ws['G3'].font = name_font
135
    ws['G3'] = reporting_start_datetime_local + "~" + reporting_end_datetime_local
136
    ws.merge_cells("G3:H3")
137
138
    # Title
139
    ws['B6'].border = f_border
140
    ws['B6'].font = name_font
141
    ws['B6'].alignment = c_c_alignment
142
    ws['B6'].fill = table_fill
143
    ws['B6'] = '名称'
144
145
    ws['C6'].border = f_border
146
    ws['C6'].alignment = c_c_alignment
147
    ws['C6'].font = name_font
148
    ws['C6'].fill = table_fill
149
    ws['C6'] = '空间'
150
151
    ca_len = len(report['energycategories'])
152
153
    for i in range(0, ca_len):
154
        col = chr(ord('D') + i)
155
        ws[col + '6'].fill = table_fill
156
        ws[col + '6'].font = name_font
157
        ws[col + '6'].alignment = c_c_alignment
158
        ws[col + '6'] = report['energycategories'][i]['name'] + \
159
            " (" + report['energycategories'][i]['unit_of_measure'] + ")"
160
        ws[col + '6'].border = f_border
161
162
    current_row_number = 7
163
    for i in range(0, len(report['combined_equipments'])):
164
165
        ws['B' + str(current_row_number)].font = title_font
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
166
        ws['B' + str(current_row_number)].border = f_border
167
        ws['B' + str(current_row_number)].alignment = c_c_alignment
168
        ws['B' + str(current_row_number)] = report['combined_equipments'][i]['combined_equipment_name']
169
170
        ws['C' + str(current_row_number)].font = title_font
171
        ws['C' + str(current_row_number)].border = f_border
172
        ws['C' + str(current_row_number)].alignment = c_c_alignment
173
        ws['C' + str(current_row_number)] = report['combined_equipments'][i]['space_name']
174
175
        ca_len = len(report['combined_equipments'][i]['values'])
176
        for j in range(0, ca_len):
177
            col = chr(ord('D') + j)
178
            ws[col + str(current_row_number)].font = data_font
179
            ws[col + str(current_row_number)].border = f_border
180
            ws[col + str(current_row_number)].alignment = c_c_alignment
181
            ws[col + str(current_row_number)] = round(report['combined_equipments'][i]['values'][j], 2)
182
183
        current_row_number += 1
184
185
    filename = str(uuid.uuid4()) + '.xlsx'
186
    wb.save(filename)
187
188
    return filename
189