Passed
Push — master ( 073478...3991b7 )
by Guangyu
18:54 queued 11s
created

excelexporters.combinedequipmentoutput.export()   B

Complexity

Conditions 5

Size

Total Lines 39
Code Lines 25

Duplication

Lines 39
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 25
dl 39
loc 39
rs 8.8133
c 0
b 0
f 0
cc 5
nop 5
1
import base64
2
import uuid
3
import os
4
from openpyxl.chart import (
5
    PieChart,
6
    LineChart,
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 View Code Duplication
def export(report,
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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 View Code Duplication
def generate_excel(report,
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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
    # Img
126
    img = Image("excelexporters/myems.png")
127
    img.width = img.width * 0.85
128
    img.height = img.height * 0.85
129
    # img = Image("myems.png")
130
    ws.add_image(img, 'B1')
131
132
    # Title
133
    ws.row_dimensions[3].height = 60
134
135
    ws['B3'].font = name_font
136
    ws['B3'].alignment = b_r_alignment
137
    ws['B3'] = 'Name:'
138
    ws['C3'].border = b_border
139
    ws['C3'].alignment = b_c_alignment
140
    ws['C3'].font = name_font
141
    ws['C3'] = name
142
143
    ws['D3'].font = name_font
144
    ws['D3'].alignment = b_r_alignment
145
    ws['D3'] = 'Period:'
146
    ws['E3'].border = b_border
147
    ws['E3'].alignment = b_c_alignment
148
    ws['E3'].font = name_font
149
    ws['E3'] = period_type
150
151
    ws['F3'].font = name_font
152
    ws['F3'].alignment = b_r_alignment
153
    ws['F3'] = 'Date:'
154
    ws['G3'].border = b_border
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
    if has_names_data_flag:
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 = 60
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
        current_row_number += 1
206
207
        ws['B' + str(current_row_number)].font = title_font
208
        ws['B' + str(current_row_number)].alignment = c_c_alignment
209
        ws['B' + str(current_row_number)].border = f_border
210
        ws['B' + str(current_row_number)] = '产出'
211
212
        col = 'C'
213
214
        for i in range(0, ca_len):
215
            ws[col + str(current_row_number)].font = name_font
216
            ws[col + str(current_row_number)].alignment = c_c_alignment
217
            ws[col + str(current_row_number)].border = f_border
218
            ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
219
220
            col = chr(ord(col) + 1)
221
222
        current_row_number += 1
223
224
        ws['B' + str(current_row_number)].font = title_font
225
        ws['B' + str(current_row_number)].alignment = c_c_alignment
226
        ws['B' + str(current_row_number)].border = f_border
227
        ws['B' + str(current_row_number)] = '环比'
228
229
        col = 'C'
230
231
        for i in range(0, ca_len):
232
            ws[col + str(current_row_number)].font = name_font
233
            ws[col + str(current_row_number)].alignment = c_c_alignment
234
            ws[col + str(current_row_number)].border = f_border
235
            ws[col + str(current_row_number)] = str(
236
                round(reporting_period_data['increment_rates'][i] * 100, 2)) + '%' \
237
                if reporting_period_data['increment_rates'][i] is not None else '-'
238
239
            col = chr(ord(col) + 1)
240
241
        current_row_number += 2
242
243
        #####################################
244
245
        has_values_data = True
246
        has_timestamps_data = True
247
248
        if 'values' not in reporting_period_data.keys() or \
249
                reporting_period_data['values'] is None or \
250
                len(reporting_period_data['values']) == 0:
251
            has_values_data = False
252
253
        if 'timestamps' not in reporting_period_data.keys() or \
254
                reporting_period_data['timestamps'] is None or \
255
                len(reporting_period_data['timestamps']) == 0 or \
256
                len(reporting_period_data['timestamps'][0]) == 0:
257
            has_timestamps_data = False
258
259
        if has_values_data and has_timestamps_data:
260
            ca_len = len(reporting_period_data['names'])
261
            time = reporting_period_data['timestamps'][0]
262
263
            ws['B' + str(current_row_number)].font = title_font
264
            ws['B' + str(current_row_number)] = name + ' 详细数据'
265
266
            current_row_number += 1
267
268
            chart_start_row_number = current_row_number
269
270
            current_row_number += ca_len * 6
271
            table_start_row_number = current_row_number
272
273
            ws.row_dimensions[current_row_number].height = 60
274
            ws['B' + str(current_row_number)].fill = table_fill
275
            ws['B' + str(current_row_number)].font = title_font
276
            ws['B' + str(current_row_number)].alignment = c_c_alignment
277
            ws['B' + str(current_row_number)].border = f_border
278
            ws['B' + str(current_row_number)] = '日期时间'
279
280
            col = 'C'
281
282
            for i in range(0, ca_len):
283
                ws[col + str(current_row_number)].fill = table_fill
284
                ws[col + str(current_row_number)].font = title_font
285
                ws[col + str(current_row_number)].alignment = c_c_alignment
286
                ws[col + str(current_row_number)].border = f_border
287
                ws[col + str(current_row_number)] = \
288
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
289
                col = chr(ord(col) + 1)
290
291
            current_row_number += 1
292
293
            for i in range(0, len(time)):
294
                ws['B' + str(current_row_number)].font = title_font
295
                ws['B' + str(current_row_number)].alignment = c_c_alignment
296
                ws['B' + str(current_row_number)].border = f_border
297
                ws['B' + str(current_row_number)] = time[i]
298
299
                col = 'C'
300
                for j in range(0, ca_len):
301
                    ws[col + str(current_row_number)].font = title_font
302
                    ws[col + str(current_row_number)].alignment = c_c_alignment
303
                    ws[col + str(current_row_number)].border = f_border
304
                    ws[col + str(current_row_number)] = round(reporting_period_data['values'][j][i], 2) \
305
                        if reporting_period_data['values'][j][i] is not None else 0.00
306
                    col = chr(ord(col) + 1)
307
308
                current_row_number += 1
309
310
            table_end_row_number = current_row_number - 1
311
312
            ws['B' + str(current_row_number)].font = title_font
313
            ws['B' + str(current_row_number)].alignment = c_c_alignment
314
            ws['B' + str(current_row_number)].border = f_border
315
            ws['B' + str(current_row_number)] = '小计'
316
317
            col = 'C'
318
319
            for i in range(0, ca_len):
320
                ws[col + str(current_row_number)].font = title_font
321
                ws[col + str(current_row_number)].alignment = c_c_alignment
322
                ws[col + str(current_row_number)].border = f_border
323
                ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
324
                col = chr(ord(col) + 1)
325
326
            current_row_number += 2
327
328
            format_time_width_number = 1.0
329
            min_len_number = 1.0
330
            min_width_number = 11.0  # format_time_width_number * min_len_number + 4 and min_width_number > 11.0
331
332
            if period_type == 'hourly':
333
                format_time_width_number = 4.0
334
                min_len_number = 2
335
                min_width_number = 12.0
336
            elif period_type == 'daily':
337
                format_time_width_number = 2.5
338
                min_len_number = 4
339
                min_width_number = 14.0
340
            elif period_type == 'monthly':
341
                format_time_width_number = 2.1
342
                min_len_number = 4
343
                min_width_number = 12.4
344
            elif period_type == 'yearly':
345
                format_time_width_number = 1.5
346
                min_len_number = 5
347
                min_width_number = 11.5
348
349
            for i in range(0, ca_len):
350
                line = LineChart()
351
                line.title = '报告期产出 - ' + \
352
                             reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
353
                labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
354
                line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number)
355
                line.add_data(line_data, titles_from_data=True)
356
                line.set_categories(labels)
357
                line_data = line.series[0]
358
                line_data.marker.symbol = "circle"
359
                line_data.smooth = True
360
                line.x_axis.crosses = 'min'
361
                line.height = 8.25
362
                line.width = format_time_width_number * len(time) if len(time) > min_len_number else min_width_number
363
                if line.width > 24:
364
                    line.width = 24
365
                line.dLbls = DataLabelList()
366
                line.dLbls.dLblPos = 't'
367
                line.dLbls.showVal = True
368
                line.dLbls.showPercent = False
369
                chart_col = 'B'
370
                chart_cell = chart_col + str(chart_start_row_number)
371
                chart_start_row_number += 6
372
                ws.add_chart(line, chart_cell)
373
374
    filename = str(uuid.uuid4()) + '.xlsx'
375
    wb.save(filename)
376
377
    return filename
378