Passed
Push — master ( 456fb9...587360 )
by Guangyu
01:59 queued 11s
created

excelexporters.tenantcost.generate_excel()   F

Complexity

Conditions 39

Size

Total Lines 478
Code Lines 362

Duplication

Lines 132
Ratio 27.62 %

Importance

Changes 0
Metric Value
cc 39
eloc 362
nop 5
dl 132
loc 478
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.tenantcost.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
        BarChart,
7
        Reference,
8
    )
9
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
10
from openpyxl.drawing.image import Image
11
from openpyxl import Workbook
12
from openpyxl.chart.label import DataLabelList
13
14
####################################################################################################################
15
# PROCEDURES
16
# Step 1: Validate the report data
17
# Step 2: Generate excel file
18
# Step 3: Encode the excel file bytes to Base64
19
####################################################################################################################
20
21
22 View Code Duplication
def export(report,
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
23
           name,
24
           reporting_start_datetime_local,
25
           reporting_end_datetime_local,
26
           period_type):
27
    ####################################################################################################################
28
    # Step 1: Validate the report data
29
    ####################################################################################################################
30
    if report is None:
31
        return None
32
    print(report)
33
34
    ####################################################################################################################
35
    # Step 2: Generate excel file from the report data
36
    ####################################################################################################################
37
    filename = generate_excel(report,
38
                              name,
39
                              reporting_start_datetime_local,
40
                              reporting_end_datetime_local,
41
                              period_type)
42
    ####################################################################################################################
43
    # Step 3: Encode the excel file to Base64
44
    ####################################################################################################################
45
    try:
46
        with open(filename, 'rb') as binary_file:
47
            binary_file_data = binary_file.read()
48
    except IOError as ex:
49
        pass
50
51
    # Base64 encode the bytes
52
    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...
53
    # get the Base64 encoded data using human-readable characters.
54
    base64_message = base64_encoded_data.decode('utf-8')
55
    # delete the file from server
56
    try:
57
        os.remove(filename)
58
    except NotImplementedError as ex:
59
        pass
60
    return base64_message
61
62
63
def generate_excel(report,
64
                   name,
65
                   reporting_start_datetime_local,
66
                   reporting_end_datetime_local,
67
                   period_type):
68
69
    wb = Workbook()
70
    ws = wb.active
71
72
    # Row height
73
    ws.row_dimensions[1].height = 118
74
    for i in range(2, 37 + 1):
75
        ws.row_dimensions[i].height = 30
76
77
    for i in range(38, 90 + 1):
78
        ws.row_dimensions[i].height = 30
79
80
    # Col width
81
    ws.column_dimensions['A'].width = 1.5
82
    ws.column_dimensions['B'].width = 20.0
83
    ws.column_dimensions['C'].width = 20.0
84
85
    for i in range(ord('D'), ord('I')):
86
        ws.column_dimensions[chr(i)].width = 15.0
87
88
    # Font
89
    name_font = Font(name='Constantia', size=15, bold=True)
90
    title_font = Font(name='宋体', size=15, bold=True)
91
    data_font = Font(name='Franklin Gothic Book', size=11)
92
93
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
94
    f_border = Border(left=Side(border_style='medium', color='00000000'),
95
                      right=Side(border_style='medium', color='00000000'),
96
                      bottom=Side(border_style='medium', color='00000000'),
97
                      top=Side(border_style='medium', color='00000000')
98
                      )
99
    b_border = Border(
100
        bottom=Side(border_style='medium', color='00000000'),
101
    )
102
103
    b_c_alignment = Alignment(vertical='bottom',
104
                              horizontal='center',
105
                              text_rotation=0,
106
                              wrap_text=False,
107
                              shrink_to_fit=False,
108
                              indent=0)
109
    c_c_alignment = Alignment(vertical='center',
110
                              horizontal='center',
111
                              text_rotation=0,
112
                              wrap_text=False,
113
                              shrink_to_fit=False,
114
                              indent=0)
115
    b_r_alignment = Alignment(vertical='bottom',
116
                              horizontal='right',
117
                              text_rotation=0,
118
                              wrap_text=False,
119
                              shrink_to_fit=False,
120
                              indent=0)
121
    c_r_alignment = Alignment(vertical='bottom',
122
                              horizontal='center',
123
                              text_rotation=0,
124
                              wrap_text=False,
125
                              shrink_to_fit=False,
126
                              indent=0)
127
    # Img
128
    img = Image("excelexporters/myems.png")
129
    # img = Image("myems.png")
130
    ws.add_image(img, 'B1')
131
132
    # Title
133
    ws['B3'].font = name_font
134
    ws['B3'].alignment = b_r_alignment
135
    ws['B3'] = 'Name:'
136
    ws['C3'].border = b_border
137
    ws['C3'].alignment = b_c_alignment
138
    ws['C3'].font = name_font
139
    ws['C3'] = name
140
141
    ws['D3'].font = name_font
142
    ws['D3'].alignment = b_r_alignment
143
    ws['D3'] = 'Period:'
144
    ws['E3'].border = b_border
145
    ws['E3'].alignment = b_c_alignment
146
    ws['E3'].font = name_font
147
    ws['E3'] = period_type
148
149
    ws['F3'].font = name_font
150
    ws['F3'].alignment = b_r_alignment
151
    ws['F3'] = 'Date:'
152
    ws.merge_cells("G3:J3")
153
    for i in range(ord('G'), ord('J') + 1):
154
        ws[chr(i) + '3'].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
159
    if "reporting_period" not in report.keys() or \
160
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
161
        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...
162
        wb.save(filename)
163
164
        return filename
165
166
    #################################################
167
168
    reporting_period_data = report['reporting_period']
169
170
    has_energy_data_flag = True
171
    if "names" not in reporting_period_data.keys() or \
172
            reporting_period_data['names'] is None or \
173
            len(reporting_period_data['names']) == 0:
174
        has_energy_data_flag = False
175
176
    if has_energy_data_flag:
177
        ws['B6'].font = title_font
178
        ws['B6'] = name+' 报告期成本'
179
180
        category = reporting_period_data['names']
181
        ca_len = len(category)
182
183
        ws['B7'].fill = table_fill
184
185
        ws['B8'].font = title_font
186
        ws['B8'].alignment = c_c_alignment
187
        ws['B8'] = '成本'
188
        ws['B8'].border = f_border
189
190
        ws['B9'].font = title_font
191
        ws['B9'].alignment = c_c_alignment
192
        ws['B9'] = '单位面积能耗'
193
        ws['B9'].border = f_border
194
195
        ws['B10'].font = title_font
196
        ws['B10'].alignment = c_c_alignment
197
        ws['B10'] = '环比'
198
        ws['B10'].border = f_border
199
200
        col = 'B'
201
202
        for i in range(0, ca_len):
203
            col = chr(ord('C') + i)
204
            ws[col + '7'].fill = table_fill
205
            ws[col + '7'].font = name_font
206
            ws[col + '7'].alignment = c_c_alignment
207
            ws[col + '7'] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
208
            ws[col + '7'].border = f_border
209
210
            ws[col + '8'].font = name_font
211
            ws[col + '8'].alignment = c_c_alignment
212
            ws[col + '8'] = round(reporting_period_data['subtotals'][i], 0)
213
            ws[col + '8'].border = f_border
214
215
            ws[col + '9'].font = name_font
216
            ws[col + '9'].alignment = c_c_alignment
217
            ws[col + '9'] = round(reporting_period_data['subtotals_per_unit_area'][i], 2)
218
            ws[col + '9'].border = f_border
219
220
            ws[col + '10'].font = name_font
221
            ws[col + '10'].alignment = c_c_alignment
222
            ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
223
                if reporting_period_data['increment_rates'][i] is not None else "-"
224
            ws[col + '10'].border = f_border
225
226
        end_col = chr(ord(col)+1)
227
        ws[end_col + '7'].fill = table_fill
228
        ws[end_col + '7'].font = name_font
229
        ws[end_col + '7'].alignment = c_c_alignment
230
        ws[end_col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")"
231
        ws[end_col + '7'].border = f_border
232
233
        ws[end_col + '8'].font = name_font
234
        ws[end_col + '8'].alignment = c_c_alignment
235
        ws[end_col + '8'] = round(reporting_period_data['total'], 0)
236
        ws[end_col + '8'].border = f_border
237
238
        ws[end_col + '9'].font = name_font
239
        ws[end_col + '9'].alignment = c_c_alignment
240
        ws[end_col + '9'] = round(reporting_period_data['total_per_unit_area'], 2)
241
        ws[end_col + '9'].border = f_border
242
243
        ws[end_col + '10'].font = name_font
244
        ws[end_col + '10'].alignment = c_c_alignment
245
        ws[end_col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \
246
            if reporting_period_data['total_increment_rate'] is not None else "-"
247
        ws[end_col + '10'].border = f_border
248
249
    else:
250
        for i in range(6, 10 + 1):
251
            ws.row_dimensions[i].height = 0.1
252
253
    #################################################
254
255
    has_ele_peak_flag = True
256
    if "toppeaks" not in reporting_period_data.keys() or \
257
            reporting_period_data['toppeaks'] is None or \
258
            len(reporting_period_data['toppeaks']) == 0:
259
        has_ele_peak_flag = False
260
261 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...
262
        ws['B12'].font = title_font
263
        ws['B12'] = name+' 分时电耗'
264
265
        ws['B13'].fill = table_fill
266
        ws['B13'].font = name_font
267
        ws['B13'].alignment = c_c_alignment
268
        ws['B13'].border = f_border
269
270
        ws['C13'].fill = table_fill
271
        ws['C13'].font = name_font
272
        ws['C13'].alignment = c_c_alignment
273
        ws['C13'].border = f_border
274
        ws['C13'] = '分时电耗'
275
276
        ws['B14'].font = title_font
277
        ws['B14'].alignment = c_c_alignment
278
        ws['B14'] = '尖'
279
        ws['B14'].border = f_border
280
281
        ws['C14'].font = title_font
282
        ws['C14'].alignment = c_c_alignment
283
        ws['C14'].border = f_border
284
        ws['C14'] = round(reporting_period_data['toppeaks'][0], 0)
285
286
        ws['B15'].font = title_font
287
        ws['B15'].alignment = c_c_alignment
288
        ws['B15'] = '峰'
289
        ws['B15'].border = f_border
290
291
        ws['C15'].font = title_font
292
        ws['C15'].alignment = c_c_alignment
293
        ws['C15'].border = f_border
294
        ws['C15'] = round(reporting_period_data['onpeaks'][0], 0)
295
296
        ws['B16'].font = title_font
297
        ws['B16'].alignment = c_c_alignment
298
        ws['B16'] = '平'
299
        ws['B16'].border = f_border
300
301
        ws['C16'].font = title_font
302
        ws['C16'].alignment = c_c_alignment
303
        ws['C16'].border = f_border
304
        ws['C16'] = round(reporting_period_data['midpeaks'][0], 0)
305
306
        ws['B17'].font = title_font
307
        ws['B17'].alignment = c_c_alignment
308
        ws['B17'] = '谷'
309
        ws['B17'].border = f_border
310
311
        ws['C17'].font = title_font
312
        ws['C17'].alignment = c_c_alignment
313
        ws['C17'].border = f_border
314
        ws['C17'] = round(reporting_period_data['offpeaks'][0], 0)
315
316
        pie = PieChart()
317
        labels = Reference(ws, min_col=2, min_row=14, max_row=17)
318
        pie_data = Reference(ws, min_col=3, min_row=13, max_row=17)
319
        pie.add_data(pie_data, titles_from_data=True)
320
        pie.set_categories(labels)
321
        pie.height = 5.25
322
        pie.width = 9
323
        s1 = pie.series[0]
324
        s1.dLbls = DataLabelList()
325
        s1.dLbls.showCatName = False
326
        s1.dLbls.showVal = True
327
        s1.dLbls.showPercent = True
328
        ws.add_chart(pie, "D13")
329
330
    else:
331
        for i in range(12, 18 + 1):
332
            ws.row_dimensions[i].height = 0.1
333
334
    ################################################
335
336
    current_row_number = 19
337
338
    has_subtotals_data_flag = True
339
    if "subtotals" not in reporting_period_data.keys() or \
340
            reporting_period_data['subtotals'] is None or \
341
            len(reporting_period_data['subtotals']) == 0:
342
        has_subtotals_data_flag = False
343
344 View Code Duplication
    if has_subtotals_data_flag:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
345
        ws['B' + str(current_row_number)].font = title_font
346
        ws['B' + str(current_row_number)] = name + ' 成本占比'
347
348
        current_row_number += 1
349
350
        table_start_row_number = current_row_number
351
352
        ws['B' + str(current_row_number)].fill = table_fill
353
        ws['B' + str(current_row_number)].font = name_font
354
        ws['B' + str(current_row_number)].alignment = c_c_alignment
355
        ws['B' + str(current_row_number)].border = f_border
356
357
        ws['C' + str(current_row_number)].fill = table_fill
358
        ws['C' + str(current_row_number)].font = name_font
359
        ws['C' + str(current_row_number)].alignment = c_c_alignment
360
        ws['C' + str(current_row_number)].border = f_border
361
        ws['C' + str(current_row_number)] = '成本占比'
362
363
        current_row_number += 1
364
365
        ca_len = len(reporting_period_data['names'])
366
367
        for i in range(0, ca_len):
368
            ws['B' + str(current_row_number)].font = title_font
369
            ws['B' + str(current_row_number)].alignment = c_c_alignment
370
            ws['B' + str(current_row_number)] = reporting_period_data['names'][i]
371
            ws['B' + str(current_row_number)].border = f_border
372
373
            ws['C' + str(current_row_number)].font = title_font
374
            ws['C' + str(current_row_number)].alignment = c_c_alignment
375
            ws['C' + str(current_row_number)].border = f_border
376
            ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
377
378
            current_row_number += 1
379
380
        table_end_row_number = current_row_number - 1
381
382
        pie = PieChart()
383
        labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
384
        pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number)
385
        pie.add_data(pie_data, titles_from_data=True)
386
        pie.set_categories(labels)
387
        pie.height = 5.25
388
        pie.width = 9
389
        s1 = pie.series[0]
390
        s1.dLbls = DataLabelList()
391
        s1.dLbls.showCatName = False
392
        s1.dLbls.showVal = True
393
        s1.dLbls.showPercent = True
394
        table_cell = 'D' + str(table_start_row_number)
395
        ws.add_chart(pie, table_cell)
396
397
        if ca_len < 4:
398
            current_row_number = current_row_number - ca_len + 4
399
400
    else:
401
        for i in range(21, 29 + 1):
402
            current_row_number = 30
403
            ws.row_dimensions[i].height = 0.1
404
405
    ###############################################
406
407
    current_row_number += 1
408
409
    has_detail_data_flag = True
410
411
    table_start_draw_flag = current_row_number + 1
412
413
    if "timestamps" not in reporting_period_data.keys() or \
414
            reporting_period_data['timestamps'] is None or \
415
            len(reporting_period_data['timestamps']) == 0:
416
        has_detail_data_flag = False
417
418
    if has_detail_data_flag:
419
        reporting_period_data = report['reporting_period']
420
        times = reporting_period_data['timestamps']
421
        ca_len = len(report['reporting_period']['names'])
422
423
        ws['B' + str(current_row_number)].font = title_font
424
        ws['B' + str(current_row_number)] = name+' 详细数据'
425
426
        table_start_row_number = (current_row_number + 1) + ca_len * 5
427
        current_row_number = table_start_row_number
428
429
        time = times[0]
430
        has_data = False
431
432
        if len(time) > 0:
433
            has_data = True
434
435
        if has_data:
436
437
            ws['B' + str(current_row_number)].fill = table_fill
438
            ws['B' + str(current_row_number)].border = f_border
439
            ws['B' + str(current_row_number)].font = title_font
440
            ws['B' + str(current_row_number)].alignment = c_c_alignment
441
            ws['B' + str(current_row_number)] = '日期时间'
442
443
            col = 'B'
444
445
            for i in range(0, ca_len):
446
                col = chr(ord('C') + i)
447
448
                ws[col + str(current_row_number)].fill = table_fill
449
                ws[col + str(current_row_number)].font = title_font
450
                ws[col + str(current_row_number)].alignment = c_c_alignment
451
                ws[col + str(current_row_number)] = reporting_period_data['names'][i] + \
452
                    " (" + reporting_period_data['units'][i] + ")"
453
                ws[col + str(current_row_number)].border = f_border
454
455
            end_col = chr(ord(col) + 1)
456
457
            ws[end_col + str(current_row_number)].fill = table_fill
458
            ws[end_col + str(current_row_number)].font = title_font
459
            ws[end_col + str(current_row_number)].alignment = c_c_alignment
460
            ws[end_col + str(current_row_number)] = "总计 (" + reporting_period_data['total_unit'] + ")"
461
            ws[end_col + str(current_row_number)].border = f_border
462
463
            current_row_number += 1
464
465
            for i in range(0, len(time)):
466
                ws['B' + str(current_row_number)].font = title_font
467
                ws['B' + str(current_row_number)].alignment = c_c_alignment
468
                ws['B' + str(current_row_number)] = time[i]
469
                ws['B' + str(current_row_number)].border = f_border
470
471
                col = 'B'
472
473
                every_day_total = 0
474
475
                for j in range(0, ca_len):
476
                    col = chr(ord('C') + j)
477
478
                    ws[col + str(current_row_number)].font = title_font
479
                    ws[col + str(current_row_number)].alignment = c_c_alignment
480
                    value = round(reporting_period_data['values'][j][i], 0)
481
                    every_day_total += value
482
                    ws[col + str(current_row_number)] = value
483
                    ws[col + str(current_row_number)].border = f_border
484
485
                end_col = chr(ord(col) + 1)
486
                ws[end_col + str(current_row_number)].font = title_font
487
                ws[end_col + str(current_row_number)].alignment = c_c_alignment
488
                ws[end_col + str(current_row_number)] = round(every_day_total, 0)
489
                ws[end_col + str(current_row_number)].border = f_border
490
491
                current_row_number += 1
492
493
            table_end_row_number = current_row_number - 1
494
495
            ws['B' + str(current_row_number)].font = title_font
496
            ws['B' + str(current_row_number)].alignment = c_c_alignment
497
            ws['B' + str(current_row_number)] = '小计'
498
            ws['B' + str(current_row_number)].border = f_border
499
500
            col = 'B'
501
502
            for i in range(0, ca_len):
503
                col = chr(ord('C') + i)
504
                ws[col + str(current_row_number)].font = title_font
505
                ws[col + str(current_row_number)].alignment = c_c_alignment
506
                ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 0)
507
                ws[col + str(current_row_number)].border = f_border
508
509
                # bar
510
                bar = BarChart()
511
                labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
512
                bar_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number)
513
                bar.add_data(bar_data, titles_from_data=True)
514
                bar.set_categories(labels)
515
                bar.height = 5.25
516
                bar.width = len(time)
517
                bar.dLbls = DataLabelList()
518
                bar.dLbls.showVal = True
519
                bar.dLbls.showPercent = True
520
                chart_col = 'B'
521
                chart_cell = chart_col + str(table_start_draw_flag + 5 * i)
522
                ws.add_chart(bar, chart_cell)
523
524
            end_col = chr(ord(col) + 1)
525
            ws[end_col + str(current_row_number)].font = title_font
526
            ws[end_col + str(current_row_number)].alignment = c_c_alignment
527
            ws[end_col + str(current_row_number)] = round(reporting_period_data['total'], 0)
528
            ws[end_col + str(current_row_number)].border = f_border
529
530
            current_row_number += 1
531
532
    else:
533
        for i in range(30, 69 + 1):
534
            current_row_number = 70
535
            ws.row_dimensions[i].height = 0.1
536
537
    filename = str(uuid.uuid4()) + '.xlsx'
538
    wb.save(filename)
539
540
    return filename
541