Passed
Push — master ( ae591e...0045d7 )
by Guangyu
07:21 queued 12s
created

excelexporters.metertracking.generate_excel()   B

Complexity

Conditions 3

Size

Total Lines 64
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 52
dl 0
loc 64
rs 8.5709
c 0
b 0
f 0
cc 3
nop 4

How to fix   Long Method   

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:

1
import base64
2
import uuid
3
import os
4
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
5
from openpyxl.drawing.image import Image
6
from openpyxl import Workbook
7
8
9
########################################################################################################################
10
# PROCEDURES
11
# Step 1: Validate the report data
12
# Step 2: Generate excelexporters file
13
# Step 3: Encode the excelexporters file to Base64
14
########################################################################################################################
15
16 View Code Duplication
def export(result, space_name, reporting_start_datetime_local, reporting_end_datetime_local):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
17
    ####################################################################################################################
18
    # Step 1: Validate the report data
19
    ####################################################################################################################
20
    if result is None:
21
        return None
22
23
    ####################################################################################################################
24
    # Step 2: Generate excel file from the report data
25
    ####################################################################################################################
26
    filename = generate_excel(result,
27
                              space_name,
28
                              reporting_start_datetime_local,
29
                              reporting_end_datetime_local)
30
    ####################################################################################################################
31
    # Step 3: Encode the excel file to Base64
32
    ####################################################################################################################
33
    binary_file_data = b''
34
    try:
35
        with open(filename, 'rb') as binary_file:
36
            binary_file_data = binary_file.read()
37
    except IOError as ex:
38
        pass
39
40
    # Base64 encode the bytes
41
    base64_encoded_data = base64.b64encode(binary_file_data)
42
    # get the Base64 encoded data using human-readable characters.
43
    base64_message = base64_encoded_data.decode('utf-8')
44
    # delete the file from server
45
    try:
46
        os.remove(filename)
47
    except NotImplementedError as ex:
48
        pass
49
    return base64_message
50
51
52
def generate_excel(report, space_name, reporting_start_datetime_local, reporting_end_datetime_local):
53
54
    wb = Workbook()
55
    ws = wb.active
56
    ws.title = "MeterTracking"
57
58
    # Column width
59
    for i in range(ord('A'), ord('H')):
60
        ws.column_dimensions[chr(i)].width = 30.0
61
62
    # Head image
63
    ws.row_dimensions[1].height = 105
64
    img = Image("excelexporters/myems.png")
65
    ws.add_image(img, 'A1')
66
67
    # Query Parameters
68
    b_r_alignment = Alignment(vertical='bottom',
69
                              horizontal='right',
70
                              text_rotation=0,
71
                              wrap_text=True,
72
                              shrink_to_fit=False,
73
                              indent=0)
74
    ws['A3'].alignment = b_r_alignment
75
    ws['A3'] = 'Space:'
76
    ws['B3'] = space_name
77
    ws['A4'].alignment = b_r_alignment
78
    ws['A4'] = 'Start Datetime:'
79
    ws['B4'] = reporting_start_datetime_local
80
    ws['A5'].alignment = b_r_alignment
81
    ws['A5'] = 'End Datetime:'
82
    ws['B5'] = reporting_end_datetime_local
83
84
    # Title
85
    title_font = Font(size=12, bold=True)
86
    ws['A6'].font = title_font
87
    ws['A6'] = 'Name'
88
    ws['B6'].font = title_font
89
    ws['B6'] = 'Space'
90
    ws['C6'].font = title_font
91
    ws['C6'] = 'Cost Center'
92
    ws['D6'].font = title_font
93
    ws['D6'] = 'Energy Category'
94
    ws['E6'].font = title_font
95
    ws['E6'] = 'Description'
96
    ws['F6'].font = title_font
97
    ws['F6'] = 'Start Value'
98
    ws['G6'].font = title_font
99
    ws['G6'] = 'End Value'
100
101
    current_row_number = 7
102
    for i in range(0, len(report['meters'])):
103
        ws['A' + str(current_row_number)] = report['meters'][i]['meter_name']
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
104
        ws['B' + str(current_row_number)] = report['meters'][i]['space_name']
105
        ws['C' + str(current_row_number)] = report['meters'][i]['cost_center_name']
106
        ws['D' + str(current_row_number)] = report['meters'][i]['energy_category_name']
107
        ws['E' + str(current_row_number)] = report['meters'][i]['description']
108
        ws['F' + str(current_row_number)] = report['meters'][i]['start_value']
109
        ws['G' + str(current_row_number)] = report['meters'][i]['end_value']
110
        current_row_number += 1
111
112
    filename = str(uuid.uuid4()) + '.xlsx'
113
    wb.save(filename)
114
115
    return filename
116