excelexporters.tenantsaving.generate_excel()   F
last analyzed

Complexity

Conditions 42

Size

Total Lines 501
Code Lines 383

Duplication

Lines 250
Ratio 49.9 %

Importance

Changes 0
Metric Value
cc 42
eloc 383
nop 5
dl 250
loc 501
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.tenantsaving.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
    LineChart,
6
    PieChart,
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
126
    # Img
127
    img = Image("excelexporters/myems.png")
128
    img.width = img.width * 0.85
129
    img.height = img.height * 0.85
130
    # img = Image("myems.png")
131
    ws.add_image(img, 'B1')
132
133
    # Title
134
    ws.row_dimensions[3].height = 60
135
136
    ws['B3'].font = name_font
137
    ws['B3'].alignment = b_r_alignment
138
    ws['B3'] = 'Name:'
139
    ws['C3'].border = b_border
140
    ws['C3'].alignment = b_c_alignment
141
    ws['C3'].font = name_font
142
    ws['C3'] = name
143
144
    ws['D3'].font = name_font
145
    ws['D3'].alignment = b_r_alignment
146
    ws['D3'] = 'Period:'
147
    ws['E3'].border = b_border
148
    ws['E3'].alignment = b_c_alignment
149
    ws['E3'].font = name_font
150
    ws['E3'] = period_type
151
152
    ws['F3'].font = name_font
153
    ws['F3'].alignment = b_r_alignment
154
    ws['F3'] = 'Date:'
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 View Code Duplication
    if has_names_data_flag:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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 = 75.0
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['units'][i] + ")"
202
203
            col = chr(ord(col) + 1)
204
205
        ws[col + str(current_row_number)].fill = table_fill
206
        ws[col + str(current_row_number)].font = name_font
207
        ws[col + str(current_row_number)].alignment = c_c_alignment
208
        ws[col + str(current_row_number)].border = f_border
209
        ws[col + str(current_row_number)] = '吨标准煤 (基线-实际) (TCE)'
210
211
        col = chr(ord(col) + 1)
212
213
        ws[col + str(current_row_number)].fill = table_fill
214
        ws[col + str(current_row_number)].font = name_font
215
        ws[col + str(current_row_number)].alignment = c_c_alignment
216
        ws[col + str(current_row_number)].border = f_border
217
        ws[col + str(current_row_number)] = '吨二氧化碳排放 (基线-实际) (TCO2E)'
218
219
        col = chr(ord(col) + 1)
220
221
        current_row_number += 1
222
223
        ws['B' + str(current_row_number)].font = title_font
224
        ws['B' + str(current_row_number)].alignment = c_c_alignment
225
        ws['B' + str(current_row_number)].border = f_border
226
        ws['B' + str(current_row_number)] = '节约'
227
228
        col = 'C'
229
230
        for i in range(0, ca_len):
231
            ws[col + str(current_row_number)].font = name_font
232
            ws[col + str(current_row_number)].alignment = c_c_alignment
233
            ws[col + str(current_row_number)].border = f_border
234
            ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_saving'][i], 2)
235
236
            col = chr(ord(col) + 1)
237
238
        ws[col + str(current_row_number)].font = name_font
239
        ws[col + str(current_row_number)].alignment = c_c_alignment
240
        ws[col + str(current_row_number)].border = f_border
241
        ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgce_saving'] / 1000, 2)
242
243
        col = chr(ord(col) + 1)
244
245
        ws[col + str(current_row_number)].font = name_font
246
        ws[col + str(current_row_number)].alignment = c_c_alignment
247
        ws[col + str(current_row_number)].border = f_border
248
        ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgco2e_saving'] / 1000, 2)
249
250
        col = chr(ord(col) + 1)
251
252
        current_row_number += 1
253
254
        ws['B' + str(current_row_number)].font = title_font
255
        ws['B' + str(current_row_number)].alignment = c_c_alignment
256
        ws['B' + str(current_row_number)].border = f_border
257
        ws['B' + str(current_row_number)] = '单位面积值'
258
259
        col = 'C'
260
261
        for i in range(0, ca_len):
262
            ws[col + str(current_row_number)].font = name_font
263
            ws[col + str(current_row_number)].alignment = c_c_alignment
264
            ws[col + str(current_row_number)].border = f_border
265
            ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_per_unit_area_saving'][i], 2)
266
267
            col = chr(ord(col) + 1)
268
269
        ws[col + str(current_row_number)].font = name_font
270
        ws[col + str(current_row_number)].alignment = c_c_alignment
271
        ws[col + str(current_row_number)].border = f_border
272
        ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgco2e_per_unit_area_saving']
273
                                                  / 1000, 2)
274
275
        col = chr(ord(col) + 1)
276
277
        ws[col + str(current_row_number)].font = name_font
278
        ws[col + str(current_row_number)].alignment = c_c_alignment
279
        ws[col + str(current_row_number)].border = f_border
280
        ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgce_per_unit_area_saving'] / 1000, 2)
281
282
        col = chr(ord(col) + 1)
283
284
        current_row_number += 1
285
286
        ws['B' + str(current_row_number)].font = title_font
287
        ws['B' + str(current_row_number)].alignment = c_c_alignment
288
        ws['B' + str(current_row_number)].border = f_border
289
        ws['B' + str(current_row_number)] = '环比'
290
291
        col = 'C'
292
293
        for i in range(0, ca_len):
294
            ws[col + str(current_row_number)].font = name_font
295
            ws[col + str(current_row_number)].alignment = c_c_alignment
296
            ws[col + str(current_row_number)].border = f_border
297
            ws[col + str(current_row_number)] = str(
298
                round(reporting_period_data['increment_rates_saving'][i] * 100, 2)) + '%' \
299
                if reporting_period_data['increment_rates_saving'][i] is not None else '-'
300
301
            col = chr(ord(col) + 1)
302
303
        ws[col + str(current_row_number)].font = name_font
304
        ws[col + str(current_row_number)].alignment = c_c_alignment
305
        ws[col + str(current_row_number)].border = f_border
306
        ws[col + str(current_row_number)] = str(
307
            round(reporting_period_data['increment_rate_in_kgce_saving'] * 100, 2)) + '%' \
308
            if reporting_period_data['increment_rate_in_kgce_saving'] is not None else '-'
309
310
        col = chr(ord(col) + 1)
311
312
        ws[col + str(current_row_number)].font = name_font
313
        ws[col + str(current_row_number)].alignment = c_c_alignment
314
        ws[col + str(current_row_number)].border = f_border
315
        ws[col + str(current_row_number)] = str(
316
            round(reporting_period_data['increment_rate_in_kgco2e_saving'] * 100, 2)) + '%' \
317
            if reporting_period_data['increment_rate_in_kgco2e_saving'] is not None else '-'
318
319
        col = chr(ord(col) + 1)
320
321
        current_row_number += 2
322
323
        ws['B' + str(current_row_number)].font = title_font
324
        ws['B' + str(current_row_number)] = name + ' 吨标准煤(TCE)占比'
325
326
        current_row_number += 1
327
        table_start_row_number = current_row_number
328
        chart_start_row_number = current_row_number
329
330
        ws.row_dimensions[current_row_number].height = 60
331
        ws['B' + str(current_row_number)].fill = table_fill
332
        ws['B' + str(current_row_number)].border = f_border
333
334
        ws['C' + str(current_row_number)].fill = table_fill
335
        ws['C' + str(current_row_number)].font = name_font
336
        ws['C' + str(current_row_number)].alignment = c_c_alignment
337
        ws['C' + str(current_row_number)].border = f_border
338
        ws['C' + str(current_row_number)] = '吨标准煤(TCE)占比'
339
340
        current_row_number += 1
341
342
        for i in range(0, ca_len):
343
            ws['B' + str(current_row_number)].font = title_font
344
            ws['B' + str(current_row_number)].alignment = c_c_alignment
345
            ws['B' + str(current_row_number)].border = f_border
346
            ws['B' + str(current_row_number)] = reporting_period_data['names'][i]
347
348
            ws['C' + str(current_row_number)].font = name_font
349
            ws['C' + str(current_row_number)].alignment = c_c_alignment
350
            ws['C' + str(current_row_number)].border = f_border
351
            ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgce_saving'][i] / 1000, 3)
352
353
            current_row_number += 1
354
355
        table_end_row_number = current_row_number - 1
356
357
        if ca_len < 4:
358
            current_row_number = current_row_number - ca_len + 4
359
360
        current_row_number += 1
361
362
        pie = PieChart()
363
        pie.title = name + ' 吨标准煤(TCE)占比'
364
        labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
365
        pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number)
366
        pie.add_data(pie_data, titles_from_data=True)
367
        pie.set_categories(labels)
368
        pie.height = 7.25
369
        pie.width = 9
370
        s1 = pie.series[0]
371
        s1.dLbls = DataLabelList()
372
        s1.dLbls.showCatName = False
373
        s1.dLbls.showVal = True
374
        s1.dLbls.showPercent = True
375
        ws.add_chart(pie, 'D' + str(chart_start_row_number))
376
377
        ws['B' + str(current_row_number)].font = title_font
378
        ws['B' + str(current_row_number)] = name + ' 吨二氧化碳排放(TCO2E)占比'
379
380
        current_row_number += 1
381
        table_start_row_number = current_row_number
382
        chart_start_row_number = current_row_number
383
384
        ws.row_dimensions[current_row_number].height = 60
385
        ws['B' + str(current_row_number)].fill = table_fill
386
        ws['B' + str(current_row_number)].border = f_border
387
388
        ws['C' + str(current_row_number)].fill = table_fill
389
        ws['C' + str(current_row_number)].font = name_font
390
        ws['C' + str(current_row_number)].alignment = c_c_alignment
391
        ws['C' + str(current_row_number)].border = f_border
392
        ws['C' + str(current_row_number)] = '吨二氧化碳排放(TCO2E)占比'
393
394
        current_row_number += 1
395
396
        for i in range(0, ca_len):
397
            ws['B' + str(current_row_number)].font = title_font
398
            ws['B' + str(current_row_number)].alignment = c_c_alignment
399
            ws['B' + str(current_row_number)].border = f_border
400
            ws['B' + str(current_row_number)] = reporting_period_data['names'][i]
401
402
            ws['C' + str(current_row_number)].font = name_font
403
            ws['C' + str(current_row_number)].alignment = c_c_alignment
404
            ws['C' + str(current_row_number)].border = f_border
405
            ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgco2e_saving'][i] / 1000, 3)
406
407
            current_row_number += 1
408
409
        table_end_row_number = current_row_number - 1
410
411
        if ca_len < 4:
412
            current_row_number = current_row_number - ca_len + 4
413
414
        current_row_number += 1
415
416
        pie = PieChart()
417
        pie.title = name + ' 吨二氧化碳排放(TCO2E)占比'
418
        labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
419
        pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number)
420
        pie.add_data(pie_data, titles_from_data=True)
421
        pie.set_categories(labels)
422
        pie.height = 7.25
423
        pie.width = 9
424
        s1 = pie.series[0]
425
        s1.dLbls = DataLabelList()
426
        s1.dLbls.showCatName = False
427
        s1.dLbls.showVal = True
428
        s1.dLbls.showPercent = True
429
        ws.add_chart(pie, 'D' + str(chart_start_row_number))
430
431
    #############################################
432
433
    has_values_saving_data = True
434
    has_timestamps_data = True
435
436
    if 'values_saving' not in reporting_period_data.keys() or \
437
            reporting_period_data['values_saving'] is None or \
438
            len(reporting_period_data['values_saving']) == 0:
439
        has_values_saving_data = False
440
441
    if 'timestamps' not in reporting_period_data.keys() or \
442
            reporting_period_data['timestamps'] is None or \
443
            len(reporting_period_data['timestamps']) == 0 or \
444
            len(reporting_period_data['timestamps'][0]) == 0:
445
        has_timestamps_data = False
446
447
    if has_values_saving_data and has_timestamps_data:
448
        ca_len = len(reporting_period_data['names'])
449
        time = reporting_period_data['timestamps'][0]
450
451
        ws['B' + str(current_row_number)].font = title_font
452
        ws['B' + str(current_row_number)] = name + ' 详细数据'
453
454
        current_row_number += 1
455
456
        chart_start_row_number = current_row_number
457
458
        current_row_number += ca_len * 6
459
        table_start_row_number = current_row_number
460
461
        ws.row_dimensions[current_row_number].height = 60
462
        ws['B' + str(current_row_number)].fill = table_fill
463
        ws['B' + str(current_row_number)].font = title_font
464
        ws['B' + str(current_row_number)].alignment = c_c_alignment
465
        ws['B' + str(current_row_number)].border = f_border
466
        ws['B' + str(current_row_number)] = '日期时间'
467
468
        col = 'C'
469
470
        for i in range(0, ca_len):
471
            ws[col + str(current_row_number)].fill = table_fill
472
            ws[col + str(current_row_number)].font = title_font
473
            ws[col + str(current_row_number)].alignment = c_c_alignment
474
            ws[col + str(current_row_number)].border = f_border
475
            ws[col + str(current_row_number)] = \
476
                reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
477
            col = chr(ord(col) + 1)
478
479
        current_row_number += 1
480
481
        for i in range(0, len(time)):
482
            ws['B' + str(current_row_number)].font = title_font
483
            ws['B' + str(current_row_number)].alignment = c_c_alignment
484
            ws['B' + str(current_row_number)].border = f_border
485
            ws['B' + str(current_row_number)] = time[i]
486
487
            col = 'C'
488
            for j in range(0, ca_len):
489
                ws[col + str(current_row_number)].font = title_font
490
                ws[col + str(current_row_number)].alignment = c_c_alignment
491
                ws[col + str(current_row_number)].border = f_border
492
                ws[col + str(current_row_number)] = round(reporting_period_data['values_saving'][j][i], 2) \
493
                    if reporting_period_data['values_saving'][j][i] is not None else 0.00
494
                col = chr(ord(col) + 1)
495
496
            current_row_number += 1
497
498
        table_end_row_number = current_row_number - 1
499
500
        ws['B' + str(current_row_number)].font = title_font
501
        ws['B' + str(current_row_number)].alignment = c_c_alignment
502
        ws['B' + str(current_row_number)].border = f_border
503
        ws['B' + str(current_row_number)] = '小计'
504
505
        col = 'C'
506
507
        for i in range(0, ca_len):
508
            ws[col + str(current_row_number)].font = title_font
509
            ws[col + str(current_row_number)].alignment = c_c_alignment
510
            ws[col + str(current_row_number)].border = f_border
511
            ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_saving'][i], 2)
512
            col = chr(ord(col) + 1)
513
514
        current_row_number += 2
515
516
        format_time_width_number = 1.0
517
        min_len_number = 1.0
518
        min_width_number = 11.0  # format_time_width_number * min_len_number + 4 and min_width_number > 11.0
519
520
        if period_type == 'hourly':
521
            format_time_width_number = 4.0
522
            min_len_number = 2
523
            min_width_number = 12.0
524
        elif period_type == 'daily':
525
            format_time_width_number = 2.5
526
            min_len_number = 4
527
            min_width_number = 14.0
528
        elif period_type == 'monthly':
529
            format_time_width_number = 2.1
530
            min_len_number = 4
531
            min_width_number = 12.4
532
        elif period_type == 'yearly':
533
            format_time_width_number = 1.5
534
            min_len_number = 5
535
            min_width_number = 11.5
536
537
        for i in range(0, ca_len):
538
            line = LineChart()
539
            line.title = '报告期节约 - ' + \
540
                reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
541
            labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
542
            line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number)
543
            line.add_data(line_data, titles_from_data=True)
544
            line.set_categories(labels)
545
            line_data = line.series[0]
546
            line_data.marker.symbol = "circle"
547
            line_data.smooth = True
548
            line.x_axis.crosses = 'min'
549
            line.height = 8.25
550
            line.width = format_time_width_number * len(time) if len(time) > min_len_number else min_width_number
551
            if line.width > 24:
552
                line.width = 24
553
            line.dLbls = DataLabelList()
554
            line.dLbls.dLblPos = 't'
555
            line.dLbls.showVal = True
556
            line.dLbls.showPercent = False
557
            chart_col = 'B'
558
            chart_cell = chart_col + str(chart_start_row_number)
559
            chart_start_row_number += 6
560
            ws.add_chart(line, chart_cell)
561
562
    filename = str(uuid.uuid4()) + '.xlsx'
563
    wb.save(filename)
564
565
    return filename
566