Passed
Push — master ( 9b1c49...b02625 )
by Guangyu
07:27 queued 13s
created

excelexporters.equipmentbatch.generate_excel()   D

Complexity

Conditions 10

Size

Total Lines 140
Code Lines 108

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 108
dl 0
loc 140
rs 4.1999
c 0
b 0
f 0
cc 10
nop 5

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like excelexporters.equipmentbatch.generate_excel() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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