excelexporters.spaceenergyitem.generate_excel()   F
last analyzed

Complexity

Conditions 49

Size

Total Lines 470
Code Lines 363

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 49
eloc 363
nop 5
dl 0
loc 470
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.spaceenergyitem.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
def generate_excel(report,
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_child_flag = True
324
        if "child_space" not in report.keys() or "energy_item_names" not in report['child_space'].keys() or \
325
                len(report['child_space']["energy_item_names"]) == 0:
326
            has_child_flag = False
327
328
        if has_child_flag:
329
            child = report['child_space']
330
331
            ws['B' + str(current_row_number)].font = title_font
332
            ws['B' + str(current_row_number)] = name + ' 子空间数据'
333
334
            current_row_number += 1
335
336
            ws.row_dimensions[current_row_number].height = 60
337
            ws['B' + str(current_row_number)].fill = table_fill
338
            ws['B' + str(current_row_number)].border = f_border
339
            ca_len = len(child['energy_item_names'])
340
341
            for i in range(0, ca_len):
342
                row = chr(ord('C') + i)
343
                ws[row + str(current_row_number)].fill = table_fill
344
                ws[row + str(current_row_number)].font = name_font
345
                ws[row + str(current_row_number)].alignment = c_c_alignment
346
                ws[row + str(current_row_number)].border = f_border
347
                ws[row + str(current_row_number)] = \
348
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
349
350
            space_len = len(child['child_space_names_array'][0])
351
352
            for i in range(0, space_len):
353
                current_row_number += 1
354
                row = str(current_row_number)
355
356
                ws['B' + row].font = name_font
357
                ws['B' + row].alignment = c_c_alignment
358
                ws['B' + row] = child['child_space_names_array'][0][i]
359
                ws['B' + row].border = f_border
360
361
                for j in range(0, ca_len):
362
                    col = chr(ord('C') + j)
363
                    ws[col + row].font = name_font
364
                    ws[col + row].alignment = c_c_alignment
365
                    ws[col + row] = round(child['subtotals_array'][j][i], 2)
366
                    ws[col + row].border = f_border
367
368
            current_row_number += 1
369
370
            # Pie
371
            for i in range(0, ca_len):
372
                pie = PieChart()
373
                labels = Reference(ws, min_col=2, min_row=current_row_number - space_len,
374
                                   max_row=current_row_number - 1)
375
                pie_data = Reference(ws, min_col=3 + i, min_row=current_row_number - space_len - 1,
376
                                     max_row=current_row_number - 1)
377
                pie.add_data(pie_data, titles_from_data=True)
378
                pie.set_categories(labels)
379
                pie.height = 6.6
380
                pie.width = 8
381
                col = chr(ord('C') + i)
382
                pie.title = ws[col + str(current_row_number - space_len - 1)].value
383
                s1 = pie.series[0]
384
                s1.dLbls = DataLabelList()
385
                s1.dLbls.showCatName = False
386
                s1.dLbls.showVal = True
387
                s1.dLbls.showPercent = True
388
                chart_cell = ''
389
                if i % 2 == 0:
390
                    chart_cell = 'B' + str(current_row_number)
391
                else:
392
                    chart_cell = 'E' + str(current_row_number)
393
                    current_row_number += 5
394
                ws.add_chart(pie, chart_cell)
395
396
            if ca_len % 2 == 1:
397
                current_row_number += 5
398
399
            current_row_number += 1
400
        #######################
401
402
        has_values_data = True
403
        has_timestamps_data = True
404
405
        if 'values' not in reporting_period_data.keys() or \
406
                reporting_period_data['values'] is None or \
407
                len(reporting_period_data['values']) == 0:
408
            has_values_data = False
409
410
        if 'timestamps' not in reporting_period_data.keys() or \
411
                reporting_period_data['timestamps'] is None or \
412
                len(reporting_period_data['timestamps']) == 0 or \
413
                len(reporting_period_data['timestamps'][0]) == 0:
414
            has_timestamps_data = False
415
416
        if has_values_data and has_timestamps_data:
417
            ca_len = len(reporting_period_data['names'])
418
            time = reporting_period_data['timestamps'][0]
419
420
            ws['B' + str(current_row_number)].font = title_font
421
            ws['B' + str(current_row_number)] = name + ' 详细数据'
422
423
            current_row_number += 1
424
425
            chart_start_row_number = current_row_number
426
427
            current_row_number += ca_len * 6
428
            table_start_row_number = current_row_number
429
430
            ws.row_dimensions[current_row_number].height = 60
431
            ws['B' + str(current_row_number)].fill = table_fill
432
            ws['B' + str(current_row_number)].font = title_font
433
            ws['B' + str(current_row_number)].alignment = c_c_alignment
434
            ws['B' + str(current_row_number)].border = f_border
435
            ws['B' + str(current_row_number)] = '日期时间'
436
437
            col = 'C'
438
439
            for i in range(0, ca_len):
440
                ws[col + str(current_row_number)].fill = table_fill
441
                ws[col + str(current_row_number)].font = title_font
442
                ws[col + str(current_row_number)].alignment = c_c_alignment
443
                ws[col + str(current_row_number)].border = f_border
444
                ws[col + str(current_row_number)] = \
445
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
446
                col = chr(ord(col) + 1)
447
448
            current_row_number += 1
449
450
            for i in range(0, len(time)):
451
                ws['B' + str(current_row_number)].font = title_font
452
                ws['B' + str(current_row_number)].alignment = c_c_alignment
453
                ws['B' + str(current_row_number)].border = f_border
454
                ws['B' + str(current_row_number)] = time[i]
455
456
                col = 'C'
457
                for j in range(0, ca_len):
458
                    ws[col + str(current_row_number)].font = title_font
459
                    ws[col + str(current_row_number)].alignment = c_c_alignment
460
                    ws[col + str(current_row_number)].border = f_border
461
                    ws[col + str(current_row_number)] = round(reporting_period_data['values'][j][i], 2) \
462
                        if reporting_period_data['values'][j][i] is not None else 0.00
463
                    col = chr(ord(col) + 1)
464
465
                current_row_number += 1
466
467
            table_end_row_number = current_row_number - 1
468
469
            ws['B' + str(current_row_number)].font = title_font
470
            ws['B' + str(current_row_number)].alignment = c_c_alignment
471
            ws['B' + str(current_row_number)].border = f_border
472
            ws['B' + str(current_row_number)] = '小计'
473
474
            col = 'C'
475
476
            for i in range(0, ca_len):
477
                ws[col + str(current_row_number)].font = title_font
478
                ws[col + str(current_row_number)].alignment = c_c_alignment
479
                ws[col + str(current_row_number)].border = f_border
480
                ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
481
                col = chr(ord(col) + 1)
482
483
            current_row_number += 2
484
485
            format_time_width_number = 1.0
486
            min_len_number = 1.0
487
            min_width_number = 11.0  # format_time_width_number * min_len_number + 4 and min_width_number > 11.0
488
489
            if period_type == 'hourly':
490
                format_time_width_number = 4.0
491
                min_len_number = 2
492
                min_width_number = 12.0
493
            elif period_type == 'daily':
494
                format_time_width_number = 2.5
495
                min_len_number = 4
496
                min_width_number = 14.0
497
            elif period_type == 'monthly':
498
                format_time_width_number = 2.1
499
                min_len_number = 4
500
                min_width_number = 12.4
501
            elif period_type == 'yearly':
502
                format_time_width_number = 1.5
503
                min_len_number = 5
504
                min_width_number = 11.5
505
506
            for i in range(0, ca_len):
507
                line = LineChart()
508
                line.title = '报告期消耗 - ' + \
509
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
510
                labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
511
                line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number)
512
                line.add_data(line_data, titles_from_data=True)
513
                line.set_categories(labels)
514
                line_data = line.series[0]
515
                line_data.marker.symbol = "circle"
516
                line_data.smooth = True
517
                line.x_axis.crosses = 'min'
518
                line.height = 8.25
519
                line.width = format_time_width_number * len(time) if len(time) > min_len_number else min_width_number
520
                if line.width > 24:
521
                    line.width = 24
522
                line.dLbls = DataLabelList()
523
                line.dLbls.dLblPos = 't'
524
                line.dLbls.showVal = True
525
                line.dLbls.showPercent = False
526
                chart_col = 'B'
527
                chart_cell = chart_col + str(chart_start_row_number)
528
                chart_start_row_number += 6
529
                ws.add_chart(line, chart_cell)
530
531
    filename = str(uuid.uuid4()) + '.xlsx'
532
    wb.save(filename)
533
534
    return filename
535
536
537
def group_by_category(category_list):
538
    category_dict = dict()
539
    for i, value in enumerate(category_list):
540
        if value not in category_dict.keys():
541
            category_dict[value] = list()
542
        category_dict[value].append(i)
543
    return category_dict
544
545