Issues (1577)

myems-api/excelexporters/equipmentbatch.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 excelexporters file
15
# Step 3: Encode the excelexporters 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
    trans = get_translation(language)
56
    trans.install()
57
    _ = trans.gettext
58
    wb = Workbook()
59
    ws = wb.active
60
    ws.title = "EquipmentBatch"
61
62
    # Row height
63
    ws.row_dimensions[1].height = 102
64
    for i in range(2, 5 + 1):
65
        ws.row_dimensions[i].height = 42
66
67
    for i in range(6, len(report['equipments']) + 15):
68
        ws.row_dimensions[i].height = 60
69
70
    # Col width
71
    ws.column_dimensions['A'].width = 1.5
72
73
    ws.column_dimensions['B'].width = 25.0
74
75
    for i in range(ord('C'), ord('L')):
76
        ws.column_dimensions[chr(i)].width = 15.0
77
78
    # Font
79
    name_font = Font(name='Arial', size=15, bold=True)
80
    title_font = Font(name='Arial', size=15, bold=True)
81
    data_font = Font(name='Franklin Gothic Book', size=11)
82
83
    table_fill = PatternFill(fill_type='solid', fgColor='90ee90')
84
    f_border = Border(left=Side(border_style='medium'),
85
                      right=Side(border_style='medium'),
86
                      bottom=Side(border_style='medium'),
87
                      top=Side(border_style='medium')
88
                      )
89
    b_border = Border(
90
        bottom=Side(border_style='medium'),
91
    )
92
93
    b_c_alignment = Alignment(vertical='bottom',
94
                              horizontal='center',
95
                              text_rotation=0,
96
                              wrap_text=True,
97
                              shrink_to_fit=False,
98
                              indent=0)
99
    c_c_alignment = Alignment(vertical='center',
100
                              horizontal='center',
101
                              text_rotation=0,
102
                              wrap_text=True,
103
                              shrink_to_fit=False,
104
                              indent=0)
105
    b_r_alignment = Alignment(vertical='bottom',
106
                              horizontal='right',
107
                              text_rotation=0,
108
                              wrap_text=True,
109
                              shrink_to_fit=False,
110
                              indent=0)
111
112
    # Img
113
    img = Image("excelexporters/myems.png")
114
    ws.add_image(img, 'A1')
115
116
    # Title
117
    ws['B3'].alignment = b_r_alignment
118
    ws['B3'] = _('Space') + ':'
119
    ws['C3'].border = b_border
120
    ws['C3'].alignment = b_c_alignment
121
    ws['C3'] = space_name
122
123
    ws['B4'].alignment = b_r_alignment
124
    ws['B4'] = _('Reporting Start Datetime') + ':'
125
    ws['C4'].border = b_border
126
    ws['C4'].alignment = b_c_alignment
127
    ws['C4'] = reporting_start_datetime_local
128
129
    ws['B5'].alignment = b_r_alignment
130
    ws['B5'] = _('Reporting End Datetime') + ':'
131
    ws['C5'].border = b_border
132
    ws['C5'].alignment = b_c_alignment
133
    ws['C5'] = reporting_end_datetime_local
134
135
    # Title
136
    ws['B6'].border = f_border
137
    ws['B6'].font = name_font
138
    ws['B6'].alignment = c_c_alignment
139
    ws['B6'].fill = table_fill
140
    ws['B6'] = _('Name')
141
142
    ws['C6'].border = f_border
143
    ws['C6'].alignment = c_c_alignment
144
    ws['C6'].font = name_font
145
    ws['C6'].fill = table_fill
146
    ws['C6'] = _('Space')
147
148
    ca_len = len(report['energycategories'])
149
150
    for i in range(0, ca_len):
151
        col = chr(ord('D') + i)
152
        ws[col + '6'].fill = table_fill
153
        ws[col + '6'].font = name_font
154
        ws[col + '6'].alignment = c_c_alignment
155
        ws[col + '6'] = report['energycategories'][i]['name'] + \
156
            " (" + report['energycategories'][i]['unit_of_measure'] + ")"
157
        ws[col + '6'].border = f_border
158
159
    current_row_number = 7
160
    for i in range(0, len(report['equipments'])):
161
162
        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...
163
        ws['B' + str(current_row_number)].border = f_border
164
        ws['B' + str(current_row_number)].alignment = c_c_alignment
165
        ws['B' + str(current_row_number)] = report['equipments'][i]['equipment_name']
166
167
        ws['C' + str(current_row_number)].font = title_font
168
        ws['C' + str(current_row_number)].border = f_border
169
        ws['C' + str(current_row_number)].alignment = c_c_alignment
170
        ws['C' + str(current_row_number)] = report['equipments'][i]['space_name']
171
172
        ca_len = len(report['equipments'][i]['values'])
173
        for j in range(0, ca_len):
174
            col = chr(ord('D') + j)
175
            ws[col + str(current_row_number)].font = data_font
176
            ws[col + str(current_row_number)].border = f_border
177
            ws[col + str(current_row_number)].alignment = c_c_alignment
178
            ws[col + str(current_row_number)] = round2(report['equipments'][i]['values'][j], 2)
179
180
        current_row_number += 1
181
182
    filename = str(uuid.uuid4()) + '.xlsx'
183
    wb.save(filename)
184
185
    return filename
186