excelexporters.tenantenergyitem.generate_excel()   F
last analyzed

Complexity

Conditions 39

Size

Total Lines 391
Code Lines 301

Duplication

Lines 391
Ratio 100 %

Importance

Changes 0
Metric Value
cc 39
eloc 301
nop 5
dl 391
loc 391
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.tenantenergyitem.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.chart import (
5
    PieChart,
6
    LineChart,
7
    BarChart,
8
    Reference,
9
)
10
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
11
from openpyxl.drawing.image import Image
12
from openpyxl import Workbook
13
from openpyxl.chart.label import DataLabelList
14
15
16
####################################################################################################################
17
# PROCEDURES
18
# Step 1: Validate the report data
19
# Step 2: Generate excel file
20
# Step 3: Encode the excel file bytes to Base64
21
####################################################################################################################
22
23
24
def export(report,
25
           name,
26
           reporting_start_datetime_local,
27
           reporting_end_datetime_local,
28
           period_type):
29
    ####################################################################################################################
30
    # Step 1: Validate the report data
31
    ####################################################################################################################
32
    if report is None:
33
        return None
34
    print(report)
35
36
    ####################################################################################################################
37
    # Step 2: Generate excel file from the report data
38
    ####################################################################################################################
39
    filename = generate_excel(report,
40
                              name,
41
                              reporting_start_datetime_local,
42
                              reporting_end_datetime_local,
43
                              period_type)
44
    ####################################################################################################################
45
    # Step 3: Encode the excel file to Base64
46
    ####################################################################################################################
47
    try:
48
        with open(filename, 'rb') as binary_file:
49
            binary_file_data = binary_file.read()
50
    except IOError as ex:
51
        pass
52
53
    # Base64 encode the bytes
54
    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...
55
    # get the Base64 encoded data using human-readable characters.
56
    base64_message = base64_encoded_data.decode('utf-8')
57
    # delete the file from server
58
    try:
59
        os.remove(filename)
60
    except NotImplementedError as ex:
61
        pass
62
    return base64_message
63
64
65 View Code Duplication
def generate_excel(report,
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
66
                   name,
67
                   reporting_start_datetime_local,
68
                   reporting_end_datetime_local,
69
                   period_type):
70
    wb = Workbook()
71
    ws = wb.active
72
73
    # Row height
74
    ws.row_dimensions[1].height = 102
75
    for i in range(2, 2000 + 1):
76
        ws.row_dimensions[i].height = 42
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='Constantia', size=15, bold=True)
88
    title_font = Font(name='宋体', 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
    c_r_alignment = Alignment(vertical='bottom',
120
                              horizontal='center',
121
                              text_rotation=0,
122
                              wrap_text=True,
123
                              shrink_to_fit=False,
124
                              indent=0)
125
    # Img
126
    img = Image("excelexporters/myems.png")
127
    img.width = img.width * 0.85
128
    img.height = img.height * 0.85
129
    # img = Image("myems.png")
130
    ws.add_image(img, 'B1')
131
132
    # Title
133
    ws.row_dimensions[3].height = 60
134
135
    ws['B3'].font = name_font
136
    ws['B3'].alignment = b_r_alignment
137
    ws['B3'] = 'Name:'
138
    ws['C3'].border = b_border
139
    ws['C3'].alignment = b_c_alignment
140
    ws['C3'].font = name_font
141
    ws['C3'] = name
142
143
    ws['D3'].font = name_font
144
    ws['D3'].alignment = b_r_alignment
145
    ws['D3'] = 'Period:'
146
    ws['E3'].border = b_border
147
    ws['E3'].alignment = b_c_alignment
148
    ws['E3'].font = name_font
149
    ws['E3'] = period_type
150
151
    ws['F3'].font = name_font
152
    ws['F3'].alignment = b_r_alignment
153
    ws['F3'] = 'Date:'
154
    ws['G3'].border = b_border
155
    ws['G3'].alignment = b_c_alignment
156
    ws['G3'].font = name_font
157
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
158
    ws.merge_cells("G3:H3")
159
160
    if "reporting_period" not in report.keys() or \
161
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
162
        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...
163
        wb.save(filename)
164
165
        return filename
166
167
    ##################################
168
169
    current_row_number = 6
170
171
    reporting_period_data = report['reporting_period']
172
173
    has_names_data_flag = True
174
175
    if "names" not in reporting_period_data.keys() or \
176
            reporting_period_data['names'] is None or \
177
            len(reporting_period_data['names']) == 0:
178
        has_names_data_flag = False
179
180
    if has_names_data_flag:
181
        ws['B' + str(current_row_number)].font = title_font
182
        ws['B' + str(current_row_number)] = name + ' 报告期消耗'
183
184
        current_row_number += 1
185
186
        category = reporting_period_data['names']
187
        ca_len = len(category)
188
189
        ws.row_dimensions[current_row_number].height = 60
190
        ws['B' + str(current_row_number)].fill = table_fill
191
        ws['B' + str(current_row_number)].border = f_border
192
193
        col = 'C'
194
195
        for i in range(0, ca_len):
196
            ws[col + str(current_row_number)].fill = table_fill
197
            ws[col + str(current_row_number)].font = name_font
198
            ws[col + str(current_row_number)].alignment = c_c_alignment
199
            ws[col + str(current_row_number)].border = f_border
200
            ws[col + str(current_row_number)] = \
201
                reporting_period_data['names'][i] + " " + reporting_period_data['energy_category_names'][i] + \
202
                " (" + reporting_period_data['units'][i] + ")"
203
204
            col = chr(ord(col) + 1)
205
206
        current_row_number += 1
207
208
        ws['B' + str(current_row_number)].font = title_font
209
        ws['B' + str(current_row_number)].alignment = c_c_alignment
210
        ws['B' + str(current_row_number)].border = f_border
211
        ws['B' + str(current_row_number)] = '消耗'
212
213
        col = 'C'
214
215
        for i in range(0, ca_len):
216
            ws[col + str(current_row_number)].font = name_font
217
            ws[col + str(current_row_number)].alignment = c_c_alignment
218
            ws[col + str(current_row_number)].border = f_border
219
            ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
220
221
            col = chr(ord(col) + 1)
222
223
        current_row_number += 1
224
225
        ws['B' + str(current_row_number)].font = title_font
226
        ws['B' + str(current_row_number)].alignment = c_c_alignment
227
        ws['B' + str(current_row_number)].border = f_border
228
        ws['B' + str(current_row_number)] = '单位面积值'
229
230
        col = 'C'
231
232
        for i in range(0, ca_len):
233
            ws[col + str(current_row_number)].font = name_font
234
            ws[col + str(current_row_number)].alignment = c_c_alignment
235
            ws[col + str(current_row_number)].border = f_border
236
            ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_per_unit_area'][i], 2)
237
238
            col = chr(ord(col) + 1)
239
240
        current_row_number += 1
241
242
        ws['B' + str(current_row_number)].font = title_font
243
        ws['B' + str(current_row_number)].alignment = c_c_alignment
244
        ws['B' + str(current_row_number)].border = f_border
245
        ws['B' + str(current_row_number)] = '环比'
246
247
        col = 'C'
248
249
        for i in range(0, ca_len):
250
            ws[col + str(current_row_number)].font = name_font
251
            ws[col + str(current_row_number)].alignment = c_c_alignment
252
            ws[col + str(current_row_number)].border = f_border
253
            ws[col + str(current_row_number)] = str(
254
                round(reporting_period_data['increment_rates'][i] * 100, 2)) + '%' \
255
                if reporting_period_data['increment_rates'][i] is not None else '-'
256
257
            col = chr(ord(col) + 1)
258
259
        current_row_number += 2
260
261
        category_dict = group_by_category(reporting_period_data['energy_category_names'])
262
263
        for category_dict_name, category_dict_values in category_dict.items():
264
265
            ws['B' + str(current_row_number)].font = title_font
266
            ws['B' + str(current_row_number)] = \
267
                name + ' ' + category_dict_name + ' (' + reporting_period_data['units'][category_dict_values[0]] + \
268
                ') 分项消耗占比'
269
270
            current_row_number += 1
271
            table_start_row_number = current_row_number
272
273
            ws['B' + str(current_row_number)].fill = table_fill
274
            ws['B' + str(current_row_number)].border = f_border
275
276
            ws['C' + str(current_row_number)].font = name_font
277
            ws['C' + str(current_row_number)].fill = table_fill
278
            ws['C' + str(current_row_number)].alignment = c_c_alignment
279
            ws['C' + str(current_row_number)].border = f_border
280
            ws['C' + str(current_row_number)] = '消耗'
281
282
            current_row_number += 1
283
284
            for i in category_dict_values:
285
                ws['B' + str(current_row_number)].font = title_font
286
                ws['B' + str(current_row_number)].alignment = c_c_alignment
287
                ws['B' + str(current_row_number)].border = f_border
288
                ws['B' + str(current_row_number)] = \
289
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
290
                ws['C' + str(current_row_number)].font = name_font
291
                ws['C' + str(current_row_number)].alignment = c_c_alignment
292
                ws['C' + str(current_row_number)].border = f_border
293
                ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 3)
294
295
                current_row_number += 1
296
297
            table_end_row_number = current_row_number - 1
298
299
            pie = PieChart()
300
            pie.title = \
301
                name + ' ' + category_dict_name + ' (' + reporting_period_data['units'][category_dict_values[0]] + \
302
                ') 分项消耗占比'
303
            labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
304
            pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number)
305
            pie.add_data(pie_data, titles_from_data=True)
306
            pie.set_categories(labels)
307
            pie.height = 6.6
308
            pie.width = 9
309
            s1 = pie.series[0]
310
            s1.dLbls = DataLabelList()
311
            s1.dLbls.showCatName = False
312
            s1.dLbls.showVal = True
313
            s1.dLbls.showPercent = True
314
            ws.add_chart(pie, 'D' + str(table_start_row_number))
315
316
            if len(category_dict_values) < 4:
317
                current_row_number = current_row_number - len(category_dict_values) + 4
318
319
            current_row_number += 1
320
321
        #######################
322
323
        has_values_data = True
324
        has_timestamps_data = True
325
326
        if 'values' not in reporting_period_data.keys() or \
327
                reporting_period_data['values'] is None or \
328
                len(reporting_period_data['values']) == 0:
329
            has_values_data = False
330
331
        if 'timestamps' not in reporting_period_data.keys() or \
332
                reporting_period_data['timestamps'] is None or \
333
                len(reporting_period_data['timestamps']) == 0 or \
334
                len(reporting_period_data['timestamps'][0]) == 0:
335
            has_timestamps_data = False
336
337
        if has_values_data and has_timestamps_data:
338
            ca_len = len(reporting_period_data['names'])
339
            time = reporting_period_data['timestamps'][0]
340
341
            ws['B' + str(current_row_number)].font = title_font
342
            ws['B' + str(current_row_number)] = name + ' 详细数据'
343
344
            current_row_number += 1
345
346
            chart_start_row_number = current_row_number
347
348
            current_row_number += ca_len * 6
349
            table_start_row_number = current_row_number
350
351
            ws.row_dimensions[current_row_number].height = 60
352
            ws['B' + str(current_row_number)].fill = table_fill
353
            ws['B' + str(current_row_number)].font = title_font
354
            ws['B' + str(current_row_number)].alignment = c_c_alignment
355
            ws['B' + str(current_row_number)].border = f_border
356
            ws['B' + str(current_row_number)] = '日期时间'
357
358
            col = 'C'
359
360
            for i in range(0, ca_len):
361
                ws[col + str(current_row_number)].fill = table_fill
362
                ws[col + str(current_row_number)].font = title_font
363
                ws[col + str(current_row_number)].alignment = c_c_alignment
364
                ws[col + str(current_row_number)].border = f_border
365
                ws[col + str(current_row_number)] = \
366
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
367
                col = chr(ord(col) + 1)
368
369
            current_row_number += 1
370
371
            for i in range(0, len(time)):
372
                ws['B' + str(current_row_number)].font = title_font
373
                ws['B' + str(current_row_number)].alignment = c_c_alignment
374
                ws['B' + str(current_row_number)].border = f_border
375
                ws['B' + str(current_row_number)] = time[i]
376
377
                col = 'C'
378
                for j in range(0, ca_len):
379
                    ws[col + str(current_row_number)].font = title_font
380
                    ws[col + str(current_row_number)].alignment = c_c_alignment
381
                    ws[col + str(current_row_number)].border = f_border
382
                    ws[col + str(current_row_number)] = round(reporting_period_data['values'][j][i], 2) \
383
                        if reporting_period_data['values'][j][i] is not None else 0.00
384
                    col = chr(ord(col) + 1)
385
386
                current_row_number += 1
387
388
            table_end_row_number = current_row_number - 1
389
390
            ws['B' + str(current_row_number)].font = title_font
391
            ws['B' + str(current_row_number)].alignment = c_c_alignment
392
            ws['B' + str(current_row_number)].border = f_border
393
            ws['B' + str(current_row_number)] = '小计'
394
395
            col = 'C'
396
397
            for i in range(0, ca_len):
398
                ws[col + str(current_row_number)].font = title_font
399
                ws[col + str(current_row_number)].alignment = c_c_alignment
400
                ws[col + str(current_row_number)].border = f_border
401
                ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
402
                col = chr(ord(col) + 1)
403
404
            current_row_number += 2
405
406
            format_time_width_number = 1.0
407
            min_len_number = 1.0
408
            min_width_number = 11.0  # format_time_width_number * min_len_number + 4 and min_width_number > 11.0
409
410
            if period_type == 'hourly':
411
                format_time_width_number = 4.0
412
                min_len_number = 2
413
                min_width_number = 12.0
414
            elif period_type == 'daily':
415
                format_time_width_number = 2.5
416
                min_len_number = 4
417
                min_width_number = 14.0
418
            elif period_type == 'monthly':
419
                format_time_width_number = 2.1
420
                min_len_number = 4
421
                min_width_number = 12.4
422
            elif period_type == 'yearly':
423
                format_time_width_number = 1.5
424
                min_len_number = 5
425
                min_width_number = 11.5
426
427
            for i in range(0, ca_len):
428
                line = LineChart()
429
                line.title = '报告期消耗 - ' + \
430
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
431
                labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
432
                line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number)
433
                line.add_data(line_data, titles_from_data=True)
434
                line.set_categories(labels)
435
                line_data = line.series[0]
436
                line_data.marker.symbol = "circle"
437
                line_data.smooth = True
438
                line.x_axis.crosses = 'min'
439
                line.height = 8.25
440
                line.width = format_time_width_number * len(time) if len(time) > min_len_number else min_width_number
441
                if line.width > 24:
442
                    line.width = 24
443
                line.dLbls = DataLabelList()
444
                line.dLbls.dLblPos = 't'
445
                line.dLbls.showVal = True
446
                line.dLbls.showPercent = False
447
                chart_col = 'B'
448
                chart_cell = chart_col + str(chart_start_row_number)
449
                chart_start_row_number += 6
450
                ws.add_chart(line, chart_cell)
451
452
    filename = str(uuid.uuid4()) + '.xlsx'
453
    wb.save(filename)
454
455
    return filename
456
457
458
def group_by_category(category_list):
459
    category_dict = dict()
460
    for i, value in enumerate(category_list):
461
        if value not in category_dict.keys():
462
            category_dict[value] = list()
463
        category_dict[value].append(i)
464
    return category_dict
465