Passed
Push — master ( bfdf5d...b890fe )
by Guangyu
17:37 queued 10s
created

excelexporters.meterbatch   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 190
Duplicated Lines 90.53 %

Importance

Changes 0
Metric Value
wmc 12
eloc 133
dl 172
loc 190
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
C generate_excel() 139 139 7
B export() 33 33 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import base64
2
import uuid
3
import os
4
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, 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
    try:
34
        with open(filename, 'rb') as binary_file:
35
            binary_file_data = binary_file.read()
36
    except IOError as ex:
37
        pass
38
39
    # Base64 encode the bytes
40
    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...
41
    # get the Base64 encoded data using human-readable characters.
42
    base64_message = base64_encoded_data.decode('utf-8')
43
    # delete the file from server
44
    try:
45
        os.remove(filename)
46
    except NotImplementedError as ex:
47
        pass
48
    return base64_message
49
50
51 View Code Duplication
def generate_excel(report, 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...
52
53
    wb = Workbook()
54
    ws = wb.active
55
    ws.title = "MeterBatch"
56
57
    # Row height
58
    ws.row_dimensions[1].height = 102
59
    for i in range(2, 5 + 1):
60
        ws.row_dimensions[i].height = 42
61
62
    for i in range(6, len(report['meters']) + 15):
63
        ws.row_dimensions[i].height = 60
64
65
    # Col width
66
    ws.column_dimensions['A'].width = 1.5
67
68
    ws.column_dimensions['B'].width = 25.0
69
70
    for i in range(ord('C'), ord('L')):
71
        ws.column_dimensions[chr(i)].width = 15.0
72
73
    # Font
74
    name_font = Font(name='Constantia', size=15, bold=True)
75
    title_font = Font(name='宋体', size=15, bold=True)
76
    data_font = Font(name='Franklin Gothic Book', size=11)
77
78
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
79
    f_border = Border(left=Side(border_style='medium', color='00000000'),
80
                      right=Side(border_style='medium', color='00000000'),
81
                      bottom=Side(border_style='medium', color='00000000'),
82
                      top=Side(border_style='medium', color='00000000')
83
                      )
84
    b_border = Border(
85
        bottom=Side(border_style='medium', color='00000000'),
86
    )
87
88
    b_c_alignment = Alignment(vertical='bottom',
89
                              horizontal='center',
90
                              text_rotation=0,
91
                              wrap_text=True,
92
                              shrink_to_fit=False,
93
                              indent=0)
94
    c_c_alignment = Alignment(vertical='center',
95
                              horizontal='center',
96
                              text_rotation=0,
97
                              wrap_text=True,
98
                              shrink_to_fit=False,
99
                              indent=0)
100
    b_r_alignment = Alignment(vertical='bottom',
101
                              horizontal='right',
102
                              text_rotation=0,
103
                              wrap_text=True,
104
                              shrink_to_fit=False,
105
                              indent=0)
106
    c_r_alignment = Alignment(vertical='bottom',
107
                              horizontal='center',
108
                              text_rotation=0,
109
                              wrap_text=True,
110
                              shrink_to_fit=False,
111
                              indent=0)
112
113
    # Img
114
    img = Image("excelexporters/myems.png")
115
    img.width = img.width * 0.85
116
    img.height = img.height * 0.85
117
    ws.add_image(img, 'B1')
118
119
    # Title
120
    ws.row_dimensions[3].height = 60
121
122
    ws['B3'].font = name_font
123
    ws['B3'].alignment = b_r_alignment
124
    ws['B3'] = '空间:'
125
    ws['C3'].border = b_border
126
    ws['C3'].alignment = b_c_alignment
127
    ws['C3'].font = name_font
128
    ws['C3'] = space_name
129
130
    ws['F3'].font = name_font
131
    ws['F3'].alignment = b_r_alignment
132
    ws['F3'] = '日期:'
133
    ws['G3'].border = b_border
134
    ws['G3'].alignment = b_c_alignment
135
    ws['G3'].font = name_font
136
    ws['G3'] = reporting_start_datetime_local + "~" + reporting_end_datetime_local
137
    ws.merge_cells("G3:H3")
138
139
    # Title
140
    ws['B6'].border = f_border
141
    ws['B6'].font = name_font
142
    ws['B6'].alignment = c_c_alignment
143
    ws['B6'].fill = table_fill
144
    ws['B6'] = '名称'
145
146
    ws['C6'].border = f_border
147
    ws['C6'].alignment = c_c_alignment
148
    ws['C6'].font = name_font
149
    ws['C6'].fill = table_fill
150
    ws['C6'] = '空间'
151
152
    ca_len = len(report['energycategories'])
153
154
    for i in range(0, ca_len):
155
        col = chr(ord('D') + i)
156
        ws[col + '6'].fill = table_fill
157
        ws[col + '6'].font = name_font
158
        ws[col + '6'].alignment = c_c_alignment
159
        ws[col + '6'] = report['energycategories'][i]['name'] + \
160
            " (" + report['energycategories'][i]['unit_of_measure'] + ")"
161
        ws[col + '6'].border = f_border
162
163
    current_row_number = 7
164
    for i in range(0, len(report['meters'])):
165
166
        ws['B' + str(current_row_number)].font = title_font
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
167
        ws['B' + str(current_row_number)].border = f_border
168
        ws['B' + str(current_row_number)].alignment = c_c_alignment
169
        ws['B' + str(current_row_number)] = report['meters'][i]['meter_name']
170
171
        ws['C' + str(current_row_number)].font = title_font
172
        ws['C' + str(current_row_number)].border = f_border
173
        ws['C' + str(current_row_number)].alignment = c_c_alignment
174
        ws['C' + str(current_row_number)] = report['meters'][i]['space_name']
175
176
        ca_len = len(report['meters'][i]['values'])
177
        for j in range(0, ca_len):
178
            col = chr(ord('D') + j)
179
            ws[col + str(current_row_number)].font = data_font
180
            ws[col + str(current_row_number)].border = f_border
181
            ws[col + str(current_row_number)].alignment = c_c_alignment
182
            ws[col + str(current_row_number)] = round(report['meters'][i]['values'][j], 2)
183
184
        current_row_number += 1
185
186
    filename = str(uuid.uuid4()) + '.xlsx'
187
    wb.save(filename)
188
189
    return filename
190