excelexporters.offlinemeterenergy.generate_excel()   F
last analyzed

Complexity

Conditions 24

Size

Total Lines 306
Code Lines 232

Duplication

Lines 306
Ratio 100 %

Importance

Changes 0
Metric Value
cc 24
eloc 232
nop 5
dl 306
loc 306
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.offlinemeterenergy.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
    BarChart,
6
    LineChart,
7
    Reference,
8
)
9
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
10
from openpyxl.drawing.image import Image
11
from openpyxl import Workbook
12
from openpyxl.chart.label import DataLabelList
13
14
15
####################################################################################################################
16
# PROCEDURES
17
# Step 1: Validate the report data
18
# Step 2: Generate excelexporters file
19
# Step 3: Encode the excelexporters file to Base64
20
####################################################################################################################
21
22 View Code Duplication
def export(result, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
23
    ####################################################################################################################
24
    # Step 1: Validate the report data
25
    ####################################################################################################################
26
    if result is None:
27
        return None
28
29
    ####################################################################################################################
30
    # Step 2: Generate excel file from the report data
31
    ####################################################################################################################
32
    filename = generate_excel(result,
33
                              name,
34
                              reporting_start_datetime_local,
35
                              reporting_end_datetime_local,
36
                              period_type)
37
    ####################################################################################################################
38
    # Step 3: Encode the excel file to Base64
39
    ####################################################################################################################
40
    try:
41
        with open(filename, 'rb') as binary_file:
42
            binary_file_data = binary_file.read()
43
    except IOError as ex:
44
        pass
45
46
    # Base64 encode the bytes
47
    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...
48
    # get the Base64 encoded data using human-readable characters.
49
    base64_message = base64_encoded_data.decode('utf-8')
50
    # delete the file from server
51
    try:
52
        os.remove(filename)
53
    except NotImplementedError as ex:
54
        pass
55
    return base64_message
56
57
58 View Code Duplication
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
59
60
    wb = Workbook()
61
    ws = wb.active
62
63
    # Row height
64
    ws.row_dimensions[1].height = 102
65
    for i in range(2, 2000 + 1):
66
        ws.row_dimensions[i].height = 42
67
68
    # for i in range(2, 11 + 1):
69
    #     ws.row_dimensions[i].height = 30
70
    #
71
    # for i in range(12, 43 + 1):
72
    #     ws.row_dimensions[i].height = 30
73
74
    # Col width
75
    ws.column_dimensions['A'].width = 1.5
76
77
    ws.column_dimensions['B'].width = 25.0
78
79
    for i in range(ord('C'), ord('L')):
80
        ws.column_dimensions[chr(i)].width = 15.0
81
82
    # Font
83
    name_font = Font(name='Constantia', size=15, bold=True)
84
    title_font = Font(name='宋体', size=15, bold=True)
85
    data_font = Font(name='Franklin Gothic Book', size=11)
86
87
    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
88
    f_border = Border(left=Side(border_style='medium', color='00000000'),
89
                      right=Side(border_style='medium', color='00000000'),
90
                      bottom=Side(border_style='medium', color='00000000'),
91
                      top=Side(border_style='medium', color='00000000')
92
                      )
93
    b_border = Border(
94
        bottom=Side(border_style='medium', color='00000000'),
95
    )
96
97
    b_c_alignment = Alignment(vertical='bottom',
98
                              horizontal='center',
99
                              text_rotation=0,
100
                              wrap_text=True,
101
                              shrink_to_fit=False,
102
                              indent=0)
103
    c_c_alignment = Alignment(vertical='center',
104
                              horizontal='center',
105
                              text_rotation=0,
106
                              wrap_text=True,
107
                              shrink_to_fit=False,
108
                              indent=0)
109
    b_r_alignment = Alignment(vertical='bottom',
110
                              horizontal='right',
111
                              text_rotation=0,
112
                              wrap_text=True,
113
                              shrink_to_fit=False,
114
                              indent=0)
115
    c_r_alignment = Alignment(vertical='bottom',
116
                              horizontal='center',
117
                              text_rotation=0,
118
                              wrap_text=True,
119
                              shrink_to_fit=False,
120
                              indent=0)
121
122
    # Img
123
    img = Image("excelexporters/myems.png")
124
    img.width = img.width * 0.85
125
    img.height = img.height * 0.85
126
    # img = Image("myems.png")
127
    ws.add_image(img, 'B1')
128
129
    # Title
130
    ws.row_dimensions[3].height = 60
131
132
    ws['B3'].font = name_font
133
    ws['B3'].alignment = b_r_alignment
134
    ws['B3'] = 'Name:'
135
    ws['C3'].border = b_border
136
    ws['C3'].alignment = b_c_alignment
137
    ws['C3'].font = name_font
138
    ws['C3'] = name
139
140
    ws['D3'].font = name_font
141
    ws['D3'].alignment = b_r_alignment
142
    ws['D3'] = 'Period:'
143
    ws['E3'].border = b_border
144
    ws['E3'].alignment = b_c_alignment
145
    ws['E3'].font = name_font
146
    ws['E3'] = period_type
147
148
    ws['F3'].font = name_font
149
    ws['F3'].alignment = b_r_alignment
150
    ws['F3'] = 'Date:'
151
    ws['G3'].border = b_border
152
    ws['G3'].alignment = b_c_alignment
153
    ws['G3'].font = name_font
154
    ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
155
    ws.merge_cells("G3:H3")
156
157
    if "reporting_period" not in report.keys() or \
158
            "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
159
        filename = str(uuid.uuid4()) + '.xlsx'
160
        wb.save(filename)
161
162
        return filename
163
164
    ################################
165
166
    has_energy_data_flag = True
167
168
    if "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
169
        has_energy_data_flag = False
170
171
    if has_energy_data_flag:
172
        ws['B6'].font = title_font
173
        ws['B6'] = name + '能耗分析'
174
175
        reporting_period_data = report['reporting_period']
176
        category = report['offline_meter']['energy_category_name']
177
        ca_len = len(category)
178
179
        ws.row_dimensions[7].height = 60
180
181
        ws['B7'].fill = table_fill
182
        ws['B7'].border = f_border
183
184
        ws['B8'].font = title_font
185
        ws['B8'].alignment = c_c_alignment
186
        ws['B8'] = '能耗'
187
        ws['B8'].border = f_border
188
189
        ws['B9'].font = title_font
190
        ws['B9'].alignment = c_c_alignment
191
        ws['B9'] = '环比'
192
        ws['B9'].border = f_border
193
194
        col = ''
195
196
        for i in range(0, ca_len):
197
            col = chr(ord('C') + i)
198
            row = '7'
199
            cell = col + row
200
            ws[col + '7'].fill = table_fill
201
            ws[col + '7'].font = name_font
202
            ws[col + '7'].alignment = c_c_alignment
203
            ws[col + '7'] = report['offline_meter']['energy_category_name'] + \
204
                " (" + report['offline_meter']['unit_of_measure'] + ")"
205
            ws[col + '7'].border = f_border
206
207
            ws[col + '8'].font = name_font
208
            ws[col + '8'].alignment = c_c_alignment
209
            ws[col + '8'] = round(reporting_period_data['total_in_category'], 2)
210
            ws[col + '8'].border = f_border
211
212
            ws[col + '9'].font = name_font
213
            ws[col + '9'].alignment = c_c_alignment
214
            ws[col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
215
                if reporting_period_data['increment_rate'] is not None else "-"
216
            ws[col + '9'].border = f_border
217
218
        # TCE TCO2E
219
        end_col = col
220
        # TCE
221
        tce_col = chr(ord(end_col) + 1)
222
        ws[tce_col + '7'].fill = table_fill
223
        ws[tce_col + '7'].font = name_font
224
        ws[tce_col + '7'].alignment = c_c_alignment
225
        ws[tce_col + '7'] = "吨标准煤 (TCE)"
226
        ws[tce_col + '7'].border = f_border
227
228
        ws[tce_col + '8'].font = name_font
229
        ws[tce_col + '8'].alignment = c_c_alignment
230
        ws[tce_col + '8'] = round(reporting_period_data['total_in_kgce'] / 1000, 2)
231
        ws[tce_col + '8'].border = f_border
232
233
        ws[tce_col + '9'].font = name_font
234
        ws[tce_col + '9'].alignment = c_c_alignment
235
        ws[tce_col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
236
            if reporting_period_data['increment_rate'] is not None else "-"
237
        ws[tce_col + '9'].border = f_border
238
239
        # TCO2E
240
        tco2e_col = chr(ord(end_col) + 2)
241
        ws[tco2e_col + '7'].fill = table_fill
242
        ws[tco2e_col + '7'].font = name_font
243
        ws[tco2e_col + '7'].alignment = c_c_alignment
244
        ws[tco2e_col + '7'] = "吨二氧化碳排放 (TCO2E)"
245
        ws[tco2e_col + '7'].border = f_border
246
247
        ws[tco2e_col + '8'].font = name_font
248
        ws[tco2e_col + '8'].alignment = c_c_alignment
249
        ws[tco2e_col + '8'] = round(reporting_period_data['total_in_kgco2e'] / 1000, 2)
250
        ws[tco2e_col + '8'].border = f_border
251
252
        ws[tco2e_col + '9'].font = name_font
253
        ws[tco2e_col + '9'].alignment = c_c_alignment
254
        ws[tco2e_col + '9'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
255
            if reporting_period_data['increment_rate'] is not None else "-"
256
        ws[tco2e_col + '9'].border = f_border
257
    else:
258
        for i in range(6, 9 + 1):
259
            ws.row_dimensions[i].height = 0.1
260
261
    #################################################
262
263
    has_energy_detail_flag = True
264
    reporting_period_data = report['reporting_period']
265
    times = reporting_period_data['timestamps']
266
267
    if "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
268
        has_energy_detail_flag = False
269
270
    if has_energy_detail_flag:
271
        reporting_period_data = report['reporting_period']
272
        category = report['offline_meter']['energy_category_name']
273
        ca_len = len(category)
274
275
        ws['B11'].font = title_font
276
        ws['B11'] = name + '详细数据'
277
278
        ws.row_dimensions[18].height = 60
279
280
        ws['B18'].fill = table_fill
281
        ws['B18'].font = title_font
282
        ws['B18'].border = f_border
283
        ws['B18'].alignment = c_c_alignment
284
        ws['B18'] = '日期时间'
285
        time = times
286
        has_data = False
287
        max_row = 0
288
        if len(time) > 0:
289
            has_data = True
290
            max_row = 18 + len(time)
291
292
        if has_data:
293
            for i in range(0, len(time)):
294
                col = 'B'
295
                row = str(19 + i)
296
297
                ws[col + row].font = title_font
298
                ws[col + row].alignment = c_c_alignment
299
                ws[col + row] = time[i]
300
                ws[col + row].border = f_border
301
302
            for i in range(0, ca_len):
303
                col = chr(ord('C') + i)
304
305
                ws[col + '18'].fill = table_fill
306
                ws[col + '18'].font = title_font
307
                ws[col + '18'].alignment = c_c_alignment
308
                ws[col + '18'] = report['offline_meter']['energy_category_name'] + \
309
                    " (" + report['offline_meter']['unit_of_measure'] + ")"
310
                ws[col + '18'].border = f_border
311
312
                time = times
313
                time_len = len(time)
314
315
                for j in range(0, time_len):
316
                    row = str(19 + j)
317
                    ws[col + row].font = title_font
318
                    ws[col + row].alignment = c_c_alignment
319
                    ws[col + row] = round(reporting_period_data['values'][j], 2)
320
                    ws[col + row].border = f_border
321
322
            line = LineChart()
323
            line.title = '报告期消耗 - ' + report['offline_meter']['energy_category_name'] + \
324
                " (" + report['offline_meter']['unit_of_measure'] + ")"
325
            labels = Reference(ws, min_col=2, min_row=19, max_row=max_row)
326
            bar_data = Reference(ws, min_col=3, min_row=18, max_row=max_row)
327
            line.add_data(bar_data, titles_from_data=True)
328
            line.set_categories(labels)
329
            line_data = line.series[0]
330
            line_data.marker.symbol = "circle"
331
            line_data.smooth = True
332
            line.x_axis.crosses = 'min'
333
            line.height = 8.25
334
            line.width = 24
335
            line.dLbls = DataLabelList()
336
            line.dLbls = DataLabelList()
337
            line.dLbls.dLblPos = 't'
338
            line.dLbls.showVal = True
339
            line.dLbls.showPercent = False
340
            ws.add_chart(line, "B12")
341
342
            col = 'B'
343
            row = str(19 + len(time))
344
345
            ws[col + row].font = title_font
346
            ws[col + row].alignment = c_c_alignment
347
            ws[col + row] = '总计'
348
            ws[col + row].border = f_border
349
350
            for i in range(0, ca_len):
351
                col = chr(ord(col) + 1)
352
                ws[col + row].font = title_font
353
                ws[col + row].alignment = c_c_alignment
354
                ws[col + row] = round(reporting_period_data['total_in_category'], 2)
355
                ws[col + row].border = f_border
356
357
    else:
358
        for i in range(11, 43 + 1):
359
            ws.row_dimensions[i].height = 0.0
360
    filename = str(uuid.uuid4()) + '.xlsx'
361
    wb.save(filename)
362
363
    return filename
364