excelexporters.virtualmeterenergy.generate_excel()   F
last analyzed

Complexity

Conditions 23

Size

Total Lines 295
Code Lines 225

Duplication

Lines 295
Ratio 100 %

Importance

Changes 0
Metric Value
cc 23
eloc 225
nop 5
dl 295
loc 295
rs 0
c 0
b 0
f 0

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.virtualmeterenergy.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 os
3
import uuid
4
5
from openpyxl import Workbook
6
from openpyxl.chart import (
7
    LineChart,
8
    BarChart,
9
    Reference,
10
    Series,
11
)
12
from openpyxl.chart.label import DataLabelList
13
from openpyxl.drawing.image import Image
14
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
15
16
17
####################################################################################################################
18
# PROCEDURES
19
# Step 1: Validate the report data
20
# Step 2: Generate excelexporters file
21
# Step 3: Encode the excelexporters file to Base64
22
####################################################################################################################
23
24 View Code Duplication
def export(result, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
25
    ####################################################################################################################
26
    # Step 1: Validate the report data
27
    ####################################################################################################################
28
    if result is None:
29
        return None
30
31
    ####################################################################################################################
32
    # Step 2: Generate excel file from the report data
33
    ####################################################################################################################
34
    filename = generate_excel(result,
35
                              name,
36
                              reporting_start_datetime_local,
37
                              reporting_end_datetime_local,
38
                              period_type)
39
    ####################################################################################################################
40
    # Step 3: Encode the excel file to Base64
41
    ####################################################################################################################
42
    try:
43
        with open(filename, 'rb') as binary_file:
44
            binary_file_data = binary_file.read()
45
    except IOError as ex:
46
        pass
47
48
    # Base64 encode the bytes
49
    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...
50
    # get the Base64 encoded data using human-readable characters.
51
    base64_message = base64_encoded_data.decode('utf-8')
52
    # delete the file from server
53
    try:
54
        os.remove(filename)
55
    except NotImplementedError as ex:
56
        pass
57
    return base64_message
58
59
60 View Code Duplication
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
61
    wb = Workbook()
62
    # todo
63
    ws = wb.active
64
65
    # Row height
66
    ws.row_dimensions[1].height = 102
67
    for i in range(2, 2000 + 1):
68
        ws.row_dimensions[i].height = 42
69
70
    # Col width
71
    ws.column_dimensions['A'].width = 1.5
72
73
    ws.column_dimensions['B'].width = 25.0
74
75
    for i in range(ord('C'), ord('L')):
76
        ws.column_dimensions[chr(i)].width = 15.0
77
78
    # Font
79
    name_font = Font(name='Constantia', size=15, bold=True)
80
    title_font = Font(name='宋体', size=15, bold=True)
81
    data_font = Font(name='Franklin Gothic Book', size=11)
82
83
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
84
    f_border = Border(left=Side(border_style='medium', color='00000000'),
85
                      right=Side(border_style='medium', color='00000000'),
86
                      bottom=Side(border_style='medium', color='00000000'),
87
                      top=Side(border_style='medium', color='00000000')
88
                      )
89
    b_border = Border(
90
        bottom=Side(border_style='medium', color='00000000'),
91
    )
92
93
    b_c_alignment = Alignment(vertical='bottom',
94
                              horizontal='center',
95
                              text_rotation=0,
96
                              wrap_text=True,
97
                              shrink_to_fit=False,
98
                              indent=0)
99
    c_c_alignment = Alignment(vertical='center',
100
                              horizontal='center',
101
                              text_rotation=0,
102
                              wrap_text=True,
103
                              shrink_to_fit=False,
104
                              indent=0)
105
    b_r_alignment = Alignment(vertical='bottom',
106
                              horizontal='right',
107
                              text_rotation=0,
108
                              wrap_text=True,
109
                              shrink_to_fit=False,
110
                              indent=0)
111
    c_r_alignment = Alignment(vertical='bottom',
112
                              horizontal='center',
113
                              text_rotation=0,
114
                              wrap_text=True,
115
                              shrink_to_fit=False,
116
                              indent=0)
117
118
    # Img
119
    img = Image("excelexporters/myems.png")
120
    img.width = img.width * 0.85
121
    img.height = img.height * 0.85
122
    # img = Image("myems.png")
123
    ws.add_image(img, 'B1')
124
125
    # Title
126
    ws.row_dimensions[3].height = 60
127
128
    ws['B3'].font = name_font
129
    ws['B3'].alignment = b_r_alignment
130
    ws['B3'] = 'Name:'
131
    ws['C3'].border = b_border
132
    ws['C3'].alignment = b_c_alignment
133
    ws['C3'].font = name_font
134
    ws['C3'] = name
135
136
    ws['D3'].font = name_font
137
    ws['D3'].alignment = b_r_alignment
138
    ws['D3'] = 'Period:'
139
    ws['E3'].border = b_border
140
    ws['E3'].alignment = b_c_alignment
141
    ws['E3'].font = name_font
142
    ws['E3'] = period_type
143
144
    ws['F3'].font = name_font
145
    ws['F3'].alignment = b_r_alignment
146
    ws['F3'] = 'Date:'
147
    ws.merge_cells("G3:H3")
148
    ws['G3'].border = b_border
149
    ws['G3'].alignment = b_c_alignment
150
    ws['G3'].font = name_font
151
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
152
153
    if "reporting_period" not in report.keys() or \
154
            "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
155
        filename = str(uuid.uuid4()) + '.xlsx'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
156
        wb.save(filename)
157
158
        return filename
159
160
    ###############################
161
162
    has_cost_data_flag = True
163
164
    if "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
165
        has_cost_data_flag = False
166
167
    if has_cost_data_flag:
168
        ws['B6'].font = title_font
169
        ws['B6'] = name + '报告期消耗'
170
171
        reporting_period_data = report['reporting_period']
172
        category = report['virtual_meter']['energy_category_name']
173
        ca_len = len(category)
174
175
        ws.row_dimensions[7].height = 60
176
        ws['B7'].fill = table_fill
177
        ws['B7'].border = f_border
178
179
        ws['B8'].font = title_font
180
        ws['B8'].alignment = c_c_alignment
181
        ws['B8'] = '能耗'
182
        ws['B8'].border = f_border
183
184
        ws['B9'].font = title_font
185
        ws['B9'].alignment = c_c_alignment
186
        ws['B9'] = '环比'
187
        ws['B9'].border = f_border
188
189
        col = 'B'
190
191
        for i in range(0, ca_len):
192
            col = chr(ord('C') + i)
193
194
            ws[col + '7'].fill = table_fill
195
            ws[col + '7'].font = name_font
196
            ws[col + '7'].alignment = c_c_alignment
197
            ws[col + '7'] = report['virtual_meter']['energy_category_name'] + " (" \
198
                + report['virtual_meter']['unit_of_measure'] + ")"
199
            ws[col + '7'].border = f_border
200
201
            ws[col + '8'].font = name_font
202
            ws[col + '8'].alignment = c_c_alignment
203
            ws[col + '8'] = round(reporting_period_data['total_in_category'], 2)
204
            ws[col + '8'].border = f_border
205
206
            ws[col + '9'].font = name_font
207
            ws[col + '9'].alignment = c_c_alignment
208
            ws[col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
209
                if reporting_period_data['increment_rate'] is not None else "-"
210
            ws[col + '9'].border = f_border
211
212
        # TCE TCO2E
213
        end_col = col
214
        # TCE
215
        tce_col = chr(ord(end_col) + 1)
216
        ws[tce_col + '7'].fill = table_fill
217
        ws[tce_col + '7'].font = name_font
218
        ws[tce_col + '7'].alignment = c_c_alignment
219
        ws[tce_col + '7'] = "吨标准煤 (TCE)"
220
        ws[tce_col + '7'].border = f_border
221
222
        ws[tce_col + '8'].font = name_font
223
        ws[tce_col + '8'].alignment = c_c_alignment
224
        ws[tce_col + '8'] = round(reporting_period_data['total_in_kgce'] / 1000, 2)
225
        ws[tce_col + '8'].border = f_border
226
227
        ws[tce_col + '9'].font = name_font
228
        ws[tce_col + '9'].alignment = c_c_alignment
229
        ws[tce_col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
230
            if reporting_period_data['increment_rate'] is not None else "-"
231
        ws[tce_col + '9'].border = f_border
232
233
        # TCO2E
234
        tco2e_col = chr(ord(end_col) + 2)
235
        ws[tco2e_col + '7'].fill = table_fill
236
        ws[tco2e_col + '7'].font = name_font
237
        ws[tco2e_col + '7'].alignment = c_c_alignment
238
        ws[tco2e_col + '7'] = "吨二氧化碳排放 (TCO2E)"
239
        ws[tco2e_col + '7'].border = f_border
240
241
        ws[tco2e_col + '8'].font = name_font
242
        ws[tco2e_col + '8'].alignment = c_c_alignment
243
        ws[tco2e_col + '8'] = round(reporting_period_data['total_in_kgco2e'] / 1000, 2)
244
        ws[tco2e_col + '8'].border = f_border
245
246
        ws[tco2e_col + '9'].font = name_font
247
        ws[tco2e_col + '9'].alignment = c_c_alignment
248
        ws[tco2e_col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
249
            if reporting_period_data['increment_rate'] is not None else "-"
250
        ws[tco2e_col + '9'].border = f_border
251
252
    else:
253
        for i in range(6, 9 + 1):
254
            ws.rows_dimensions[i].height = 0.1
255
256
    ######################################
257
258
    has_cost_detail_flag = True
259
    reporting_period_data = report['reporting_period']
260
    category = report['virtual_meter']['energy_category_name']
261
    ca_len = len(category)
262
    times = reporting_period_data['timestamps']
263
264
    if "values" not in reporting_period_data.keys() or len(reporting_period_data['values']) == 0:
265
        has_cost_detail_flag = False
266
267
    if has_cost_detail_flag:
268
        ws['B11'].font = title_font
269
        ws['B11'] = name + '详细数据'
270
271
        ws.row_dimensions[18].height = 60
272
        ws['B18'].fill = table_fill
273
        ws['B18'].font = title_font
274
        ws['B18'].border = f_border
275
        ws['B18'].alignment = c_c_alignment
276
        ws['B18'] = '日期时间'
277
        time = times
278
        has_data = False
279
        max_row = 0
280
        if len(time) > 0:
281
            has_data = True
282
            max_row = 18 + len(time)
283
284
        if has_data:
285
286
            end_data_row_number = 19
287
288
            for i in range(0, len(time)):
289
                col = 'B'
290
                end_data_row_number = 19 + i
291
                row = str(end_data_row_number)
292
293
                ws[col + row].font = title_font
294
                ws[col + row].alignment = c_c_alignment
295
                ws[col + row] = time[i]
296
                ws[col + row].border = f_border
297
298
            ws['B' + str(end_data_row_number + 1)].font = title_font
299
            ws['B' + str(end_data_row_number + 1)].alignment = c_c_alignment
300
            ws['B' + str(end_data_row_number + 1)] = '总计'
301
            ws['B' + str(end_data_row_number + 1)].border = f_border
302
303
            for i in range(0, ca_len):
304
305
                col = chr(ord('C') + i)
306
307
                ws[col + '18'].fill = table_fill
308
                ws[col + '18'].font = title_font
309
                ws[col + '18'].alignment = c_c_alignment
310
                ws[col + '18'] = report['virtual_meter']['energy_category_name'] + " (" \
311
                    + report['virtual_meter']['unit_of_measure'] + ")"
312
                ws[col + '18'].border = f_border
313
314
                time = times
315
                time_len = len(time)
316
317
                for j in range(0, time_len):
318
                    row = str(19 + j)
319
320
                    ws[col + row].font = title_font
321
                    ws[col + row].alignment = c_c_alignment
322
                    ws[col + row] = round(reporting_period_data['values'][j], 2)
323
                    ws[col + row].border = f_border
324
325
                ws[col + str(end_data_row_number + 1)].font = title_font
326
                ws[col + str(end_data_row_number + 1)].alignment = c_c_alignment
327
                ws[col + str(end_data_row_number + 1)] = round(reporting_period_data['total_in_category'], 2)
328
                ws[col + str(end_data_row_number + 1)].border = f_border
329
330
            line = LineChart()
331
            labels = Reference(ws, min_col=2, min_row=19, max_row=max_row)
332
            line_data = Reference(ws, min_col=3, min_row=18, max_row=max_row)
333
            line.series.append(Series(line_data, title_from_data=True))
334
            line.set_categories(labels)
335
            line_data = line.series[0]
336
            line_data.marker.symbol = "circle"
337
            line_data.smooth = True
338
            line.x_axis.crosses = 'min'
339
            line.title = '报告期消耗 - ' + report['virtual_meter']['energy_category_name'] + \
340
                         " (" + report['virtual_meter']['unit_of_measure'] + ")"
341
            line.dLbls = DataLabelList()
342
            line.dLbls.dLblPos = 't'
343
            line.dLbls.showVal = True
344
            line.height = 8.25
345
            line.width = 24
346
            ws.add_chart(line, "B12")
347
    else:
348
        for i in range(11, 43 + 1):
349
            ws.row_dimensions[i].height = 0.0
350
351
    filename = str(uuid.uuid4()) + '.xlsx'
352
    wb.save(filename)
353
354
    return filename
355