Issues (1577)

myems-api/excelexporters/combinedequipmentbatch.py (2 issues)

1
import base64
2
from core.utilities import get_translation
3
import os
4
import uuid
5
from openpyxl import Workbook
6
from openpyxl.drawing.image import Image
7
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
8
from core.utilities import round2
9
10
11
########################################################################################################################
12
# PROCEDURES
13
# Step 1: Validate the report data
14
# Step 2: Generate excel file from the report data
15
# Step 3: Encode the excel file to Base64
16
########################################################################################################################
17
def export(result, space_name, reporting_start_datetime_local, reporting_end_datetime_local, language):
18
    ####################################################################################################################
19
    # Step 1: Validate the report data
20
    ####################################################################################################################
21
    if result is None:
22
        return None
23
24
    ####################################################################################################################
25
    # Step 2: Generate excel file from the report data
26
    ####################################################################################################################
27
    filename = generate_excel(result,
28
                              space_name,
29
                              reporting_start_datetime_local,
30
                              reporting_end_datetime_local,
31
                              language)
32
    ####################################################################################################################
33
    # Step 3: Encode the excel file to Base64
34
    ####################################################################################################################
35
    binary_file_data = b''
36
    try:
37
        with open(filename, 'rb') as binary_file:
38
            binary_file_data = binary_file.read()
39
    except IOError as ex:
40
        print(str(ex))
41
42
    # Base64 encode the bytes
43
    base64_encoded_data = base64.b64encode(binary_file_data)
44
    # get the Base64 encoded data using human-readable characters.
45
    base64_message = base64_encoded_data.decode('utf-8')
46
    # delete the file from server
47
    try:
48
        os.remove(filename)
49
    except NotImplementedError as ex:
50
        print(str(ex))
51
    return base64_message
52
53
54 View Code Duplication
def generate_excel(report, space_name, reporting_start_datetime_local, reporting_end_datetime_local, language):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
55
56
    trans = get_translation(language)
57
    trans.install()
58
    _ = trans.gettext
59
60
    wb = Workbook()
61
    ws = wb.active
62
    ws.title = "CombinedEquipmentBatch"
63
64
    # Row height
65
    ws.row_dimensions[1].height = 102
66
    for i in range(2, 5 + 1):
67
        ws.row_dimensions[i].height = 42
68
69
    for i in range(6, len(report['combined_equipments']) + 15):
70
        ws.row_dimensions[i].height = 60
71
72
    # Col width
73
    ws.column_dimensions['A'].width = 1.5
74
75
    ws.column_dimensions['B'].width = 25.0
76
77
    for i in range(ord('C'), ord('L')):
78
        ws.column_dimensions[chr(i)].width = 15.0
79
80
    # Font
81
    name_font = Font(name='Arial', size=15, bold=True)
82
    title_font = Font(name='Arial', size=15, bold=True)
83
    data_font = Font(name='Franklin Gothic Book', size=11)
84
85
    table_fill = PatternFill(fill_type='solid', fgColor='90ee90')
86
    f_border = Border(left=Side(border_style='medium'),
87
                      right=Side(border_style='medium'),
88
                      bottom=Side(border_style='medium'),
89
                      top=Side(border_style='medium')
90
                      )
91
    b_border = Border(
92
        bottom=Side(border_style='medium'),
93
    )
94
95
    b_c_alignment = Alignment(vertical='bottom',
96
                              horizontal='center',
97
                              text_rotation=0,
98
                              wrap_text=True,
99
                              shrink_to_fit=False,
100
                              indent=0)
101
    c_c_alignment = Alignment(vertical='center',
102
                              horizontal='center',
103
                              text_rotation=0,
104
                              wrap_text=True,
105
                              shrink_to_fit=False,
106
                              indent=0)
107
    b_r_alignment = Alignment(vertical='bottom',
108
                              horizontal='right',
109
                              text_rotation=0,
110
                              wrap_text=True,
111
                              shrink_to_fit=False,
112
                              indent=0)
113
114
    # Img
115
    img = Image("excelexporters/myems.png")
116
    ws.add_image(img, 'A1')
117
118
    # Title
119
    ws['B3'].alignment = b_r_alignment
120
    ws['B3'] = _('Space') + ':'
121
    ws['C3'].border = b_border
122
    ws['C3'].alignment = b_c_alignment
123
    ws['C3'] = space_name
124
125
    ws['B4'].alignment = b_r_alignment
126
    ws['B4'] = _('Reporting Start Datetime') + ':'
127
    ws['C4'].border = b_border
128
    ws['C4'].alignment = b_c_alignment
129
    ws['C4'] = reporting_start_datetime_local
130
131
    ws['B5'].alignment = b_r_alignment
132
    ws['B5'] = _('Reporting End Datetime') + ':'
133
    ws['C5'].border = b_border
134
    ws['C5'].alignment = b_c_alignment
135
    ws['C5'] = reporting_end_datetime_local
136
137
    # Title
138
    ws['B6'].border = f_border
139
    ws['B6'].font = name_font
140
    ws['B6'].alignment = c_c_alignment
141
    ws['B6'].fill = table_fill
142
    ws['B6'] = _('Name')
143
144
    ws['C6'].border = f_border
145
    ws['C6'].alignment = c_c_alignment
146
    ws['C6'].font = name_font
147
    ws['C6'].fill = table_fill
148
    ws['C6'] = _('Space')
149
150
    ca_len = len(report['energycategories'])
151
152
    for i in range(0, ca_len):
153
        col = chr(ord('D') + i)
154
        ws[col + '6'].fill = table_fill
155
        ws[col + '6'].font = name_font
156
        ws[col + '6'].alignment = c_c_alignment
157
        ws[col + '6'] = report['energycategories'][i]['name'] + \
158
            " (" + report['energycategories'][i]['unit_of_measure'] + ")"
159
        ws[col + '6'].border = f_border
160
161
    current_row_number = 7
162
    for i in range(0, len(report['combined_equipments'])):
163
164
        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...
165
        ws['B' + str(current_row_number)].border = f_border
166
        ws['B' + str(current_row_number)].alignment = c_c_alignment
167
        ws['B' + str(current_row_number)] = report['combined_equipments'][i]['combined_equipment_name']
168
169
        ws['C' + str(current_row_number)].font = title_font
170
        ws['C' + str(current_row_number)].border = f_border
171
        ws['C' + str(current_row_number)].alignment = c_c_alignment
172
        ws['C' + str(current_row_number)] = report['combined_equipments'][i]['space_name']
173
174
        ca_len = len(report['combined_equipments'][i]['values'])
175
        for j in range(0, ca_len):
176
            col = chr(ord('D') + j)
177
            ws[col + str(current_row_number)].font = data_font
178
            ws[col + str(current_row_number)].border = f_border
179
            ws[col + str(current_row_number)].alignment = c_c_alignment
180
            ws[col + str(current_row_number)] = round2(report['combined_equipments'][i]['values'][j], 2)
181
182
        current_row_number += 1
183
184
    filename = str(uuid.uuid4()) + '.xlsx'
185
    wb.save(filename)
186
187
    return filename
188