excelexporters.spacecost.generate_excel()   F
last analyzed

Complexity

Conditions 41

Size

Total Lines 521
Code Lines 396

Duplication

Lines 155
Ratio 29.75 %

Importance

Changes 0
Metric Value
cc 41
eloc 396
nop 5
dl 155
loc 521
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.spacecost.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
    # for i in range(2, 37 + 1):
79
    #     ws.row_dimensions[i].height = 30
80
    #
81
    # for i in range(38, 69 + 1):
82
    #     ws.row_dimensions[i].height = 30
83
84
    # Col width
85
    ws.column_dimensions['A'].width = 1.5
86
87
    ws.column_dimensions['B'].width = 25.0
88
89
    for i in range(ord('C'), ord('L')):
90
        ws.column_dimensions[chr(i)].width = 15.0
91
92
    # Font
93
    name_font = Font(name='Constantia', size=15, bold=True)
94
    title_font = Font(name='宋体', size=15, bold=True)
95
    data_font = Font(name='Franklin Gothic Book', size=11)
96
97
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
98
    f_border = Border(left=Side(border_style='medium', color='00000000'),
99
                      right=Side(border_style='medium', color='00000000'),
100
                      bottom=Side(border_style='medium', color='00000000'),
101
                      top=Side(border_style='medium', color='00000000')
102
                      )
103
    b_border = Border(
104
        bottom=Side(border_style='medium', color='00000000'),
105
    )
106
107
    b_c_alignment = Alignment(vertical='bottom',
108
                              horizontal='center',
109
                              text_rotation=0,
110
                              wrap_text=True,
111
                              shrink_to_fit=False,
112
                              indent=0)
113
    c_c_alignment = Alignment(vertical='center',
114
                              horizontal='center',
115
                              text_rotation=0,
116
                              wrap_text=True,
117
                              shrink_to_fit=False,
118
                              indent=0)
119
    b_r_alignment = Alignment(vertical='bottom',
120
                              horizontal='right',
121
                              text_rotation=0,
122
                              wrap_text=True,
123
                              shrink_to_fit=False,
124
                              indent=0)
125
    c_r_alignment = Alignment(vertical='bottom',
126
                              horizontal='center',
127
                              text_rotation=0,
128
                              wrap_text=True,
129
                              shrink_to_fit=False,
130
                              indent=0)
131
132
    # Img
133
    img = Image("excelexporters/myems.png")
134
    img.width = img.width * 0.85
135
    img.height = img.height * 0.85
136
    # img = Image("myems.png")
137
    ws.add_image(img, 'B1')
138
139
    # Title
140
    ws.row_dimensions[3].height = 60
141
142
    ws['B3'].font = name_font
143
    ws['B3'].alignment = b_r_alignment
144
    ws['B3'] = 'Name:'
145
    ws['C3'].border = b_border
146
    ws['C3'].alignment = b_c_alignment
147
    ws['C3'].font = name_font
148
    ws['C3'] = name
149
150
    ws['D3'].font = name_font
151
    ws['D3'].alignment = b_r_alignment
152
    ws['D3'] = 'Period:'
153
    ws['E3'].border = b_border
154
    ws['E3'].alignment = b_c_alignment
155
    ws['E3'].font = name_font
156
    ws['E3'] = period_type
157
158
    ws['F3'].font = name_font
159
    ws['F3'].alignment = b_r_alignment
160
    ws['F3'] = 'Date:'
161
    ws['G3'].border = b_border
162
    ws['G3'].alignment = b_c_alignment
163
    ws['G3'].font = name_font
164
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
165
    ws.merge_cells("G3:H3")
166
167
    if "reporting_period" not in report.keys() or \
168
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
169
        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...
170
        wb.save(filename)
171
172
        return filename
173
174
    ##################################
175
176
    reporting_period_data = report['reporting_period']
177
178
    has_cost_data_flag = True
179
180
    if "names" not in reporting_period_data.keys() or \
181
            reporting_period_data['names'] is None or \
182
            len(reporting_period_data['names']) == 0:
183
        has_cost_data_flag = False
184
185 View Code Duplication
    if has_cost_data_flag:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
186
        ws['B6'].font = title_font
187
        ws['B6'] = name + ' 报告期成本'
188
189
        category = reporting_period_data['names']
190
        ca_len = len(category)
191
192
        ws.row_dimensions[7].height = 60
193
        ws['B7'].fill = table_fill
194
        ws['B7'].border = f_border
195
196
        ws['B8'].font = title_font
197
        ws['B8'].alignment = c_c_alignment
198
        ws['B8'] = '成本'
199
        ws['B8'].border = f_border
200
201
        ws['B9'].font = title_font
202
        ws['B9'].alignment = c_c_alignment
203
        ws['B9'] = '单位面积值'
204
        ws['B9'].border = f_border
205
206
        ws['B10'].font = title_font
207
        ws['B10'].alignment = c_c_alignment
208
        ws['B10'] = '环比'
209
        ws['B10'].border = f_border
210
211
        col = ''
212
213
        for i in range(0, ca_len):
214
            col = chr(ord('C') + i)
215
216
            ws[col + '7'].fill = table_fill
217
            ws[col + '7'].font = name_font
218
            ws[col + '7'].alignment = c_c_alignment
219
            ws[col + '7'] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
220
            ws[col + '7'].border = f_border
221
222
            ws[col + '8'].font = name_font
223
            ws[col + '8'].alignment = c_c_alignment
224
            ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2)
225
            ws[col + '8'].border = f_border
226
227
            ws[col + '9'].font = name_font
228
            ws[col + '9'].alignment = c_c_alignment
229
            ws[col + '9'] = round(reporting_period_data['subtotals_per_unit_area'][i], 2)
230
            ws[col + '9'].border = f_border
231
232
            ws[col + '10'].font = name_font
233
            ws[col + '10'].alignment = c_c_alignment
234
            ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
235
                if reporting_period_data['increment_rates'][i] is not None else "-"
236
            ws[col + '10'].border = f_border
237
238
        col = chr(ord(col) + 1)
239
240
        ws[col + '7'].fill = table_fill
241
        ws[col + '7'].font = name_font
242
        ws[col + '7'].alignment = c_c_alignment
243
        ws[col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")"
244
        ws[col + '7'].border = f_border
245
246
        ws[col + '8'].font = name_font
247
        ws[col + '8'].alignment = c_c_alignment
248
        ws[col + '8'] = round(reporting_period_data['total'], 2)
249
        ws[col + '8'].border = f_border
250
251
        ws[col + '9'].font = name_font
252
        ws[col + '9'].alignment = c_c_alignment
253
        ws[col + '9'] = round(reporting_period_data['total_per_unit_area'], 2)
254
        ws[col + '9'].border = f_border
255
256
        ws[col + '10'].font = name_font
257
        ws[col + '10'].alignment = c_c_alignment
258
        ws[col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \
259
            if reporting_period_data['total_increment_rate'] is not None else "-"
260
        ws[col + '10'].border = f_border
261
262
    else:
263
        for i in range(6, 10 + 1):
264
            ws.row_dimensions[i].height = 0.1
265
266
    ##############################
267
268
    has_ele_peak_flag = True
269
    if "toppeaks" not in reporting_period_data.keys() or \
270
            reporting_period_data['toppeaks'] is None or \
271
            len(reporting_period_data['toppeaks']) == 0:
272
        has_ele_peak_flag = False
273
274 View Code Duplication
    if has_ele_peak_flag:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
275
        ws['B12'].font = title_font
276
        ws['B12'] = name + '分时用电成本'
277
278
        ws.row_dimensions[13].height = 60
279
        ws['B13'].fill = table_fill
280
        ws['B13'].font = name_font
281
        ws['B13'].alignment = c_c_alignment
282
        ws['B13'].border = f_border
283
284
        ws['C13'].fill = table_fill
285
        ws['C13'].font = name_font
286
        ws['C13'].alignment = c_c_alignment
287
        ws['C13'].border = f_border
288
        ws['C13'] = '分时用电成本'
289
290
        ws['B14'].font = title_font
291
        ws['B14'].alignment = c_c_alignment
292
        ws['B14'] = '尖'
293
        ws['B14'].border = f_border
294
295
        ws['C14'].font = title_font
296
        ws['C14'].alignment = c_c_alignment
297
        ws['C14'].border = f_border
298
        ws['C14'] = round(reporting_period_data['toppeaks'][0], 2)
299
300
        ws['B15'].font = title_font
301
        ws['B15'].alignment = c_c_alignment
302
        ws['B15'] = '峰'
303
        ws['B15'].border = f_border
304
305
        ws['C15'].font = title_font
306
        ws['C15'].alignment = c_c_alignment
307
        ws['C15'].border = f_border
308
        ws['C15'] = round(reporting_period_data['onpeaks'][0], 2)
309
310
        ws['B16'].font = title_font
311
        ws['B16'].alignment = c_c_alignment
312
        ws['B16'] = '平'
313
        ws['B16'].border = f_border
314
315
        ws['C16'].font = title_font
316
        ws['C16'].alignment = c_c_alignment
317
        ws['C16'].border = f_border
318
        ws['C16'] = round(reporting_period_data['midpeaks'][0], 2)
319
320
        ws['B17'].font = title_font
321
        ws['B17'].alignment = c_c_alignment
322
        ws['B17'] = '谷'
323
        ws['B17'].border = f_border
324
325
        ws['C17'].font = title_font
326
        ws['C17'].alignment = c_c_alignment
327
        ws['C17'].border = f_border
328
        ws['C17'] = round(reporting_period_data['offpeaks'][0], 2)
329
330
        pie = PieChart()
331
        pie.title = name + '分时用电成本'
332
        labels = Reference(ws, min_col=2, min_row=14, max_row=17)
333
        pie_data = Reference(ws, min_col=3, min_row=13, max_row=17)
334
        pie.add_data(pie_data, titles_from_data=True)
335
        pie.set_categories(labels)
336
        pie.height = 7.25
337
        pie.width = 9
338
        s1 = pie.series[0]
339
        s1.dLbls = DataLabelList()
340
        s1.dLbls.showCatName = False
341
        s1.dLbls.showVal = True
342
        s1.dLbls.showPercent = True
343
344
        ws.add_chart(pie, "D13")
345
346
    else:
347
        for i in range(12, 18 + 1):
348
            ws.row_dimensions[i].height = 0.1
349
350
    ##################################
351
    current_row_number = 19
352
353
    has_child_flag = True
354
    if "child_space" not in report.keys() or "energy_category_names" not in report['child_space'].keys() or \
355
            len(report['child_space']["energy_category_names"]) == 0:
356
        has_child_flag = False
357
358
    if has_child_flag:
359
        child = report['child_space']
360
361
        ws['B' + str(current_row_number)].font = title_font
362
        ws['B' + str(current_row_number)] = name + ' 子空间数据'
363
364
        current_row_number += 1
365
366
        ws.row_dimensions[current_row_number].height = 60
367
        ws['B' + str(current_row_number)].fill = table_fill
368
        ws['B' + str(current_row_number)].border = f_border
369
        ca_len = len(child['energy_category_names'])
370
371
        col = ''
372
373
        for i in range(0, ca_len):
374
            col = chr(ord('C') + i)
375
            ws[col + str(current_row_number)].fill = table_fill
376
            ws[col + str(current_row_number)].font = title_font
377
            ws[col + str(current_row_number)].alignment = c_c_alignment
378
            ws[col + str(current_row_number)].border = f_border
379
            ws[col + str(current_row_number)] = child['energy_category_names'][i] + ' (' + child['units'][i] + ')'
380
381
        col = chr(ord(col) + 1)
382
        ws[col + str(current_row_number)].fill = table_fill
383
        ws[col + str(current_row_number)].font = title_font
384
        ws[col + str(current_row_number)].alignment = c_c_alignment
385
        ws[col + str(current_row_number)].border = f_border
386
        ws[col + str(current_row_number)] = '总计 (' + report['reporting_period']['total_unit'] + ')'
387
388
        space_len = len(child['child_space_names_array'][0])
389
390
        for i in range(0, space_len):
391
            current_row_number += 1
392
            row = str(current_row_number)
393
394
            ws['B' + row].font = name_font
395
            ws['B' + row].alignment = c_c_alignment
396
            ws['B' + row] = child['child_space_names_array'][0][i]
397
            ws['B' + row].border = f_border
398
399
            col = ''
400
            every_day_sum = 0
401
402
            for j in range(0, ca_len):
403
                col = chr(ord('C') + j)
404
                ws[col + row].font = name_font
405
                ws[col + row].alignment = c_c_alignment
406
                every_day_sum += child['subtotals_array'][j][i]
407
                ws[col + row] = round(child['subtotals_array'][j][i], 2)
408
                ws[col + row].border = f_border
409
410
            col = chr(ord(col) + 1)
411
            ws[col + row].font = name_font
412
            ws[col + row].alignment = c_c_alignment
413
            ws[col + row] = round(every_day_sum, 2)
414
            ws[col + row].border = f_border
415
416
        current_row_number += 1
417
418
        # Pie
419
        for i in range(0, ca_len):
420
            pie = PieChart()
421
            labels = Reference(ws, min_col=2, min_row=current_row_number - space_len, max_row=current_row_number - 1)
422
            pie_data = Reference(ws, min_col=3 + i, min_row=current_row_number - space_len - 1,
423
                                 max_row=current_row_number - 1)
424
            pie.add_data(pie_data, titles_from_data=True)
425
            pie.set_categories(labels)
426
            pie.height = 6.6
427
            pie.width = 8
428
            col = chr(ord('C') + i)
429
            pie.title = ws[col + '20'].value
430
            s1 = pie.series[0]
431
            s1.dLbls = DataLabelList()
432
            s1.dLbls.showCatName = False
433
            s1.dLbls.showVal = True
434
            s1.dLbls.showPercent = True
435
            chart_cell = ''
436
            if i % 2 == 0:
437
                chart_cell = 'B' + str(current_row_number)
438
            else:
439
                chart_cell = 'E' + str(current_row_number)
440
                current_row_number += 5
441
            ws.add_chart(pie, chart_cell)
442
443
            # chart_col = chr(ord('B') + 2 * i)
444
            # chart_cell = chart_col + str(current_row_number)
445
            # ws.add_chart(pie, chart_cell)
446
        if ca_len % 2 == 1:
447
            current_row_number += 5
448
449
    # else:
450
    #     for i in range(19, 36 + 1):
451
    #         current_row_number = 36
452
    #         ws.row_dimensions[i].height = 0.1
453
454
    current_row_number += 1
455
456
    #############################################
457
    reporting_period_data = report['reporting_period']
458
    times = reporting_period_data['timestamps']
459
    has_detail_data_flag = True
460
    ca_len = len(report['reporting_period']['names'])
461
    table_row = (current_row_number + 1) + ca_len * 6
462
    if "timestamps" not in reporting_period_data.keys() or \
463
            reporting_period_data['timestamps'] is None or \
464
            len(reporting_period_data['timestamps']) == 0:
465
        has_detail_data_flag = False
466
467
    if has_detail_data_flag:
468
        ws['B' + str(current_row_number)].font = title_font
469
        ws['B' + str(current_row_number)] = name + ' 详细数据'
470
471
        ws.row_dimensions[table_row].height = 60
472
        ws['B' + str(table_row)].fill = table_fill
473
        ws['B' + str(table_row)].font = title_font
474
        ws['B' + str(table_row)].border = f_border
475
        ws['B' + str(table_row)].alignment = c_c_alignment
476
        ws['B' + str(table_row)] = '日期时间'
477
        time = times[0]
478
        has_data = False
479
        max_row = 0
480
        if len(time) > 0:
481
            has_data = True
482
            max_row = table_row + len(time)
483
484
        if has_data:
485
            for i in range(0, len(time)):
486
                col = 'B'
487
                row = str(table_row + 1 + i)
488
                ws[col + row].font = title_font
489
                ws[col + row].alignment = c_c_alignment
490
                ws[col + row] = time[i]
491
                ws[col + row].border = f_border
492
493
            for i in range(0, ca_len):
494
495
                col = chr(ord('C') + i)
496
497
                ws[col + str(table_row)].fill = table_fill
498
                ws[col + str(table_row)].font = title_font
499
                ws[col + str(table_row)].alignment = c_c_alignment
500
                ws[col + str(table_row)] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][
501
                    i] + ")"
502
                ws[col + str(table_row)].border = f_border
503
504
                # 39 data
505
                time = times[i]
506
                time_len = len(time)
507
508
                for j in range(0, time_len):
509
                    row = str(table_row + 1 + j)
510
                    ws[col + row].font = title_font
511
                    ws[col + row].alignment = c_c_alignment
512
                    ws[col + row] = round(reporting_period_data['values'][i][j], 2)
513
                    ws[col + row].border = f_border
514
515
                line = LineChart()
516
                line.title = \
517
                    '报告期成本 - ' + reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
518
                labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row)
519
                line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row)
520
                line.add_data(line_data, titles_from_data=True)
521
                line.set_categories(labels)
522
                line_data = line.series[0]
523
                line_data.marker.symbol = "circle"
524
                line_data.smooth = True
525
                line.x_axis.crosses = 'min'
526
                line.height = 8.25
527
                line.width = 24
528
                line.dLbls = DataLabelList()
529
                line.dLbls.dLblPos = 't'
530
                line.dLbls.showVal = True
531
                line.dLbls.showPercent = False
532
                chart_col = 'B'
533
                chart_cell = chart_col + str(current_row_number + 1 + 6 * i)
534
                ws.add_chart(line, chart_cell)
535
536
            row = str(max_row + 1)
537
538
            ws['B' + row].font = title_font
539
            ws['B' + row].alignment = c_c_alignment
540
            ws['B' + row] = '小计'
541
            ws['B' + row].border = f_border
542
543
            col = ''
544
545
            for i in range(0, ca_len):
546
                col = chr(ord('C') + i)
547
                row = str(max_row + 1)
548
                ws[col + row].font = title_font
549
                ws[col + row].alignment = c_c_alignment
550
                ws[col + row] = round(reporting_period_data['subtotals'][i], 2)
551
                ws[col + row].border = f_border
552
553
            col = chr(ord(col) + 1)
554
555
            ws[col + str(table_row)].fill = table_fill
556
            ws[col + str(table_row)].font = title_font
557
            ws[col + str(table_row)].alignment = c_c_alignment
558
            ws[col + str(table_row)] = '总计 (' + report['reporting_period']['total_unit'] + ')'
559
            ws[col + str(table_row)].border = f_border
560
561
            total_sum = 0
562
563
            for j in range(0, len(time)):
564
                row = str(table_row + 1 + j)
565
                ws[col + row].font = title_font
566
                ws[col + row].alignment = c_c_alignment
567
                every_day_sum = reporting_period_values_every_day_sum(reporting_period_data, j, ca_len)
568
                total_sum += every_day_sum
569
                ws[col + row] = round(every_day_sum, 2)
570
                ws[col + row].border = f_border
571
572
            row = str(table_row + 1 + len(time))
573
            ws[col + row].font = title_font
574
            ws[col + row].alignment = c_c_alignment
575
            ws[col + row] = round(total_sum, 2)
576
            ws[col + row].border = f_border
577
578
    else:
579
        for i in range(37, 69 + 1):
580
            ws.row_dimensions[i].height = 0.1
581
582
    filename = str(uuid.uuid4()) + '.xlsx'
583
    wb.save(filename)
584
585
    return filename
586
587
588
def reporting_period_values_every_day_sum(reporting_period_data, every_day_index, ca_len):
589
    every_day_sum = 0
590
    for i in range(0, ca_len):
591
        every_day_sum += reporting_period_data['values'][i][every_day_index]
592
593
    return every_day_sum
594