Passed
Push — master ( bd66cb...d24938 )
by Guangyu
02:35 queued 10s
created

excelexporters.storecost.generate_excel()   F

Complexity

Conditions 39

Size

Total Lines 479
Code Lines 362

Duplication

Lines 132
Ratio 27.56 %

Importance

Changes 0
Metric Value
cc 39
eloc 362
nop 5
dl 132
loc 479
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.storecost.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
def export(report,
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:I3")
153
    for i in range(ord('G'), ord('I') + 1):
154
        ws[chr(i) + '3'].border = b_border
155
156
    ws['G3'].alignment = b_c_alignment
157
    ws['G3'].font = name_font
158
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
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
    reporting_period_data = report['reporting_period']
170
171
    has_energy_data_flag = True
172
    if "names" not in reporting_period_data.keys() or \
173
            reporting_period_data['names'] is None or \
174
            len(reporting_period_data['names']) == 0:
175
        has_energy_data_flag = False
176
177
    if has_energy_data_flag:
178
        ws['B6'].font = title_font
179
        ws['B6'] = name+' 报告期成本'
180
181
        category = reporting_period_data['names']
182
        ca_len = len(category)
183
184
        ws['B7'].fill = table_fill
185
186
        ws['B8'].font = title_font
187
        ws['B8'].alignment = c_c_alignment
188
        ws['B8'] = '成本'
189
        ws['B8'].border = f_border
190
191
        ws['B9'].font = title_font
192
        ws['B9'].alignment = c_c_alignment
193
        ws['B9'] = '单位面积能耗'
194
        ws['B9'].border = f_border
195
196
        ws['B10'].font = title_font
197
        ws['B10'].alignment = c_c_alignment
198
        ws['B10'] = '环比'
199
        ws['B10'].border = f_border
200
201
        col = 'B'
202
203
        for i in range(0, ca_len):
204
            col = chr(ord('C') + i)
205
            ws[col + '7'].fill = table_fill
206
            ws[col + '7'].font = name_font
207
            ws[col + '7'].alignment = c_c_alignment
208
            ws[col + '7'] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
209
            ws[col + '7'].border = f_border
210
211
            ws[col + '8'].font = name_font
212
            ws[col + '8'].alignment = c_c_alignment
213
            ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2)
214
            ws[col + '8'].border = f_border
215
216
            ws[col + '9'].font = name_font
217
            ws[col + '9'].alignment = c_c_alignment
218
            ws[col + '9'] = round(reporting_period_data['subtotals_per_unit_area'][i], 2)
219
            ws[col + '9'].border = f_border
220
221
            ws[col + '10'].font = name_font
222
            ws[col + '10'].alignment = c_c_alignment
223
            ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
224
                if reporting_period_data['increment_rates'][i] is not None else "-"
225
            ws[col + '10'].border = f_border
226
227
        end_col = chr(ord(col)+1)
228
        ws[end_col + '7'].fill = table_fill
229
        ws[end_col + '7'].font = name_font
230
        ws[end_col + '7'].alignment = c_c_alignment
231
        ws[end_col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")"
232
        ws[end_col + '7'].border = f_border
233
234
        ws[end_col + '8'].font = name_font
235
        ws[end_col + '8'].alignment = c_c_alignment
236
        ws[end_col + '8'] = round(reporting_period_data['total'], 2)
237
        ws[end_col + '8'].border = f_border
238
239
        ws[end_col + '9'].font = name_font
240
        ws[end_col + '9'].alignment = c_c_alignment
241
        ws[end_col + '9'] = round(reporting_period_data['total_per_unit_area'], 2)
242
        ws[end_col + '9'].border = f_border
243
244
        ws[end_col + '10'].font = name_font
245
        ws[end_col + '10'].alignment = c_c_alignment
246
        ws[end_col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \
247
            if reporting_period_data['total_increment_rate'] is not None else "-"
248
        ws[end_col + '10'].border = f_border
249
250
    else:
251
        for i in range(6, 10 + 1):
252
            ws.row_dimensions[i].height = 0.1
253
254
    #################################################
255
256
    has_ele_peak_flag = True
257
    if "toppeaks" not in reporting_period_data.keys() or \
258
            reporting_period_data['toppeaks'] is None or \
259
            len(reporting_period_data['toppeaks']) == 0:
260
        has_ele_peak_flag = False
261
262 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...
263
        ws['B12'].font = title_font
264
        ws['B12'] = name+' 分时电耗'
265
266
        ws['B13'].fill = table_fill
267
        ws['B13'].font = name_font
268
        ws['B13'].alignment = c_c_alignment
269
        ws['B13'].border = f_border
270
271
        ws['C13'].fill = table_fill
272
        ws['C13'].font = name_font
273
        ws['C13'].alignment = c_c_alignment
274
        ws['C13'].border = f_border
275
        ws['C13'] = '分时电耗'
276
277
        ws['B14'].font = title_font
278
        ws['B14'].alignment = c_c_alignment
279
        ws['B14'] = '尖'
280
        ws['B14'].border = f_border
281
282
        ws['C14'].font = title_font
283
        ws['C14'].alignment = c_c_alignment
284
        ws['C14'].border = f_border
285
        ws['C14'] = round(reporting_period_data['toppeaks'][0], 2)
286
287
        ws['B15'].font = title_font
288
        ws['B15'].alignment = c_c_alignment
289
        ws['B15'] = '峰'
290
        ws['B15'].border = f_border
291
292
        ws['C15'].font = title_font
293
        ws['C15'].alignment = c_c_alignment
294
        ws['C15'].border = f_border
295
        ws['C15'] = round(reporting_period_data['onpeaks'][0], 2)
296
297
        ws['B16'].font = title_font
298
        ws['B16'].alignment = c_c_alignment
299
        ws['B16'] = '平'
300
        ws['B16'].border = f_border
301
302
        ws['C16'].font = title_font
303
        ws['C16'].alignment = c_c_alignment
304
        ws['C16'].border = f_border
305
        ws['C16'] = round(reporting_period_data['midpeaks'][0], 2)
306
307
        ws['B17'].font = title_font
308
        ws['B17'].alignment = c_c_alignment
309
        ws['B17'] = '谷'
310
        ws['B17'].border = f_border
311
312
        ws['C17'].font = title_font
313
        ws['C17'].alignment = c_c_alignment
314
        ws['C17'].border = f_border
315
        ws['C17'] = round(reporting_period_data['offpeaks'][0], 2)
316
317
        pie = PieChart()
318
        labels = Reference(ws, min_col=2, min_row=14, max_row=17)
319
        pie_data = Reference(ws, min_col=3, min_row=13, max_row=17)
320
        pie.add_data(pie_data, titles_from_data=True)
321
        pie.set_categories(labels)
322
        pie.height = 5.25
323
        pie.width = 8
324
        s1 = pie.series[0]
325
        s1.dLbls = DataLabelList()
326
        s1.dLbls.showCatName = False
327
        s1.dLbls.showVal = True
328
        s1.dLbls.showPercent = True
329
        ws.add_chart(pie, "D13")
330
331
    else:
332
        for i in range(12, 18 + 1):
333
            ws.row_dimensions[i].height = 0.1
334
335
    ################################################
336
337
    current_row_number = 19
338
339
    has_subtotals_data_flag = True
340
    if "subtotals" not in reporting_period_data.keys() or \
341
            reporting_period_data['subtotals'] is None or \
342
            len(reporting_period_data['subtotals']) == 0:
343
        has_subtotals_data_flag = False
344
345 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...
346
        ws['B' + str(current_row_number)].font = title_font
347
        ws['B' + str(current_row_number)] = name + ' 成本占比'
348
349
        current_row_number += 1
350
351
        table_start_row_number = current_row_number
352
353
        ws['B' + str(current_row_number)].fill = table_fill
354
        ws['B' + str(current_row_number)].font = name_font
355
        ws['B' + str(current_row_number)].alignment = c_c_alignment
356
        ws['B' + str(current_row_number)].border = f_border
357
358
        ws['C' + str(current_row_number)].fill = table_fill
359
        ws['C' + str(current_row_number)].font = name_font
360
        ws['C' + str(current_row_number)].alignment = c_c_alignment
361
        ws['C' + str(current_row_number)].border = f_border
362
        ws['C' + str(current_row_number)] = '成本占比'
363
364
        current_row_number += 1
365
366
        ca_len = len(reporting_period_data['names'])
367
368
        for i in range(0, ca_len):
369
            ws['B' + str(current_row_number)].font = title_font
370
            ws['B' + str(current_row_number)].alignment = c_c_alignment
371
            ws['B' + str(current_row_number)] = reporting_period_data['names'][i]
372
            ws['B' + str(current_row_number)].border = f_border
373
374
            ws['C' + str(current_row_number)].font = title_font
375
            ws['C' + str(current_row_number)].alignment = c_c_alignment
376
            ws['C' + str(current_row_number)].border = f_border
377
            ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
378
379
            current_row_number += 1
380
381
        table_end_row_number = current_row_number - 1
382
383
        pie = PieChart()
384
        labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
385
        pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number)
386
        pie.add_data(pie_data, titles_from_data=True)
387
        pie.set_categories(labels)
388
        pie.height = 5.25
389
        pie.width = 8
390
        s1 = pie.series[0]
391
        s1.dLbls = DataLabelList()
392
        s1.dLbls.showCatName = False
393
        s1.dLbls.showVal = True
394
        s1.dLbls.showPercent = True
395
        table_cell = 'D' + str(table_start_row_number)
396
        ws.add_chart(pie, table_cell)
397
398
        if ca_len < 4:
399
            current_row_number = current_row_number - ca_len + 4
400
401
    else:
402
        for i in range(21, 29 + 1):
403
            current_row_number = 30
404
            ws.row_dimensions[i].height = 0.1
405
406
    ###############################################
407
408
    current_row_number += 1
409
410
    has_detail_data_flag = True
411
412
    table_start_draw_flag = current_row_number + 1
413
414
    if "timestamps" not in reporting_period_data.keys() or \
415
            reporting_period_data['timestamps'] is None or \
416
            len(reporting_period_data['timestamps']) == 0:
417
        has_detail_data_flag = False
418
419
    if has_detail_data_flag:
420
        reporting_period_data = report['reporting_period']
421
        times = reporting_period_data['timestamps']
422
        ca_len = len(report['reporting_period']['names'])
423
424
        ws['B' + str(current_row_number)].font = title_font
425
        ws['B' + str(current_row_number)] = name+' 详细数据'
426
427
        table_start_row_number = (current_row_number + 1) + ca_len * 5
428
        current_row_number = table_start_row_number
429
430
        time = times[0]
431
        has_data = False
432
433
        if len(time) > 0:
434
            has_data = True
435
436
        if has_data:
437
438
            ws['B' + str(current_row_number)].fill = table_fill
439
            ws['B' + str(current_row_number)].border = f_border
440
            ws['B' + str(current_row_number)].font = title_font
441
            ws['B' + str(current_row_number)].alignment = c_c_alignment
442
            ws['B' + str(current_row_number)] = '日期时间'
443
444
            col = 'B'
445
446
            for i in range(0, ca_len):
447
                col = chr(ord('C') + i)
448
449
                ws[col + str(current_row_number)].fill = table_fill
450
                ws[col + str(current_row_number)].font = title_font
451
                ws[col + str(current_row_number)].alignment = c_c_alignment
452
                ws[col + str(current_row_number)] = reporting_period_data['names'][i] + \
453
                    " (" + reporting_period_data['units'][i] + ")"
454
                ws[col + str(current_row_number)].border = f_border
455
456
            end_col = chr(ord(col) + 1)
457
458
            ws[end_col + str(current_row_number)].fill = table_fill
459
            ws[end_col + str(current_row_number)].font = title_font
460
            ws[end_col + str(current_row_number)].alignment = c_c_alignment
461
            ws[end_col + str(current_row_number)] = "总计 (" + reporting_period_data['total_unit'] + ")"
462
            ws[end_col + str(current_row_number)].border = f_border
463
464
            current_row_number += 1
465
466
            for i in range(0, len(time)):
467
                ws['B' + str(current_row_number)].font = title_font
468
                ws['B' + str(current_row_number)].alignment = c_c_alignment
469
                ws['B' + str(current_row_number)] = time[i]
470
                ws['B' + str(current_row_number)].border = f_border
471
472
                col = 'B'
473
474
                every_day_total = 0
475
476
                for j in range(0, ca_len):
477
                    col = chr(ord('C') + j)
478
479
                    ws[col + str(current_row_number)].font = title_font
480
                    ws[col + str(current_row_number)].alignment = c_c_alignment
481
                    value = round(reporting_period_data['values'][j][i], 2)
482
                    every_day_total += value
483
                    ws[col + str(current_row_number)] = value
484
                    ws[col + str(current_row_number)].border = f_border
485
486
                end_col = chr(ord(col) + 1)
487
                ws[end_col + str(current_row_number)].font = title_font
488
                ws[end_col + str(current_row_number)].alignment = c_c_alignment
489
                ws[end_col + str(current_row_number)] = round(every_day_total, 2)
490
                ws[end_col + str(current_row_number)].border = f_border
491
492
                current_row_number += 1
493
494
            table_end_row_number = current_row_number - 1
495
496
            ws['B' + str(current_row_number)].font = title_font
497
            ws['B' + str(current_row_number)].alignment = c_c_alignment
498
            ws['B' + str(current_row_number)] = '小计'
499
            ws['B' + str(current_row_number)].border = f_border
500
501
            col = 'B'
502
503
            for i in range(0, ca_len):
504
                col = chr(ord('C') + i)
505
                ws[col + str(current_row_number)].font = title_font
506
                ws[col + str(current_row_number)].alignment = c_c_alignment
507
                ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
508
                ws[col + str(current_row_number)].border = f_border
509
510
                # bar
511
                bar = BarChart()
512
                labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
513
                bar_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number)
514
                bar.add_data(bar_data, titles_from_data=True)
515
                bar.set_categories(labels)
516
                bar.height = 4.9
517
                bar.width = 16
518
                bar.dLbls = DataLabelList()
519
                bar.dLbls.showVal = True
520
                bar.dLbls.showPercent = True
521
                chart_col = 'B'
522
                chart_cell = chart_col + str(table_start_draw_flag + 5 * i)
523
                ws.add_chart(bar, chart_cell)
524
525
            end_col = chr(ord(col) + 1)
526
            ws[end_col + str(current_row_number)].font = title_font
527
            ws[end_col + str(current_row_number)].alignment = c_c_alignment
528
            ws[end_col + str(current_row_number)] = round(reporting_period_data['total'], 2)
529
            ws[end_col + str(current_row_number)].border = f_border
530
531
            current_row_number += 1
532
533
    else:
534
        for i in range(30, 69 + 1):
535
            current_row_number = 70
536
            ws.row_dimensions[i].height = 0.1
537
538
    filename = str(uuid.uuid4()) + '.xlsx'
539
    wb.save(filename)
540
541
    return filename
542