-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParsingExcel.py
385 lines (325 loc) · 16.3 KB
/
ParsingExcel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import uuid
import xlrd
from xlrd import open_workbook
from xlrd import dump
from xlrd.sheet import ctype_text
from openpyxl import Workbook
import json
import pika
import base64
import io
import re
from io import BytesIO
#import pandas as pd
import openpyxl
#import parser
import publisher
credentials = pika.PlainCredentials(username='user', password='password')
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='54.144.236.23', port='5672', credentials=credentials))
channel = connection.channel()
channel.queue_declare(queue='hello', durable=False)
counter = 1
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
excel = body
excel_dict = json.loads(excel)
encoding_data = excel_dict["base64buffer"]
decoded_data = base64.b64decode(encoding_data)
file_extension = excel_dict["fileName"]
userId = excel_dict["userId"]
filename = excel_dict["fileName"]
curr_date = excel_dict["curr_date"]
message_format = {"userid": userId, "base64buffer": base64_message,
"date": curr_date, "fileName": filename}
message = json.dumps(message_format)
print(userId)
print(filename)
if "base64buffer" in excel_dict:
if str(file_extension).split(".")[1] == 'xls':
print('excel format : xls')
try:
wbb1 = Workbook()
ws = wbb1.active
#xl_workbook = open_workbook('c:\om\exampleMasterCard.xls') # for read a file type
xl_workbook = open_workbook(file_contents=decoded_data, on_demand=True)
sheet_names = xl_workbook.sheet_names()
#print(sheet_names)
xl_sheet = xl_workbook.sheet_by_name(sheet_names[0])
xl_sheet = xl_workbook.sheet_by_index(0)
#print('Sheet name: %s' % xl_sheet.name)
row = xl_sheet.row(0)
# print (row)
#print('(Column #) type:value')
for idx, cell_obj in enumerate(row):
cell_type_str = ctype_text.get(cell_obj.ctype, 'unknown type')
#print('(%s) %s %s' % (idx, cell_type_str, cell_obj.value))
num_cols = xl_sheet.ncols # Number of columns
for row_idx in range(0, xl_sheet.nrows): # Iterate through rows
#print('-' * 40)
#print('Row: %s' % row_idx) # Print row number
for col_idx in range(0, num_cols): # Iterate through columns
cell_obj = xl_sheet.cell(row_idx, col_idx) # Get cell object by row, col
#print('Column: [%s] cell_obj: [%s]' % (col_idx, cell_obj))
ws.cell(row=row_idx + 1, column=col_idx + 1).value = cell_obj.value
f1 = 'c:\\OM\\output-xls-' + str(uuid.uuid4()) + '.xlsx'
wbb1.save(filename=f1)
workbook = openpyxl.load_workbook(f1)
# wb = load_workbook(workbook)
wb1 = workbook.active
mr = wb1.max_row
mc = wb1.max_column
match = wb1.cell(row=1, column=1)
if match.value == None:
print("ISRACARD")
wb1.delete_cols(3, 2)
sheet = wb1
alist = []
blist = []
wbb = Workbook()
ws = wbb.active
x = ['תאריך עסקה', 'שם בית העסק', 'סכום עסקה', 'קטגוריה', 'מספר כרטיס']
counter = 1
for i in x:
ws.cell(row=1, column=counter, value=i)
counter += 1
for i in range(4, mr):
b3 = sheet.cell(row=i, column=1)
s = str(b3.value).split(" ")
r = re.compile('[0-9]{4}')
newlist = list(filter(r.match, s))
list1 = [newlist, i]
if newlist != []:
alist.append(i) # add row number for cars number to list
blist.append(', '.join(newlist)) # add cards number to list
else:
continue
alist.append(mr + 5)
for a in range(0, len(alist) - 1):
for i in range(alist[a] + 3, alist[a + 1] - 2):
for j in range(1, 4):
# reading cell value from source excel file
c = wb1.cell(row=i, column=j)
# writing the read value to destination excel file
ws.cell(row=i - 5, column=j).value = c.value
ws.cell(row=i - 5, column=5).value = str(blist[a])
for j in range(1, 4):
for i in range(1, mr):
if ws.cell(row=i, column=1).value is None:
ws.delete_rows(i)
else:
continue
f = 'c:\\OM\\output-isracard-' + str(uuid.uuid4()) + '.xlsx'
wbb.save(filename=f)
# channel.queue_declare(queue='Yogevhello', durable=True)
with open(f, 'rb') as binary_file:
# print(binary_file)
binary_file_data = binary_file.read()
base64_encoded_data = base64.b64encode(binary_file_data)
base64_message = base64_encoded_data.decode('utf-8')
print("Before publish to yogev")
# wwc = {"userid": "Eldar", "time": "10/04/2020", "base64buffer": base64_message}
# message_format = {"userid": userId, "time": curr_date, "base64buffer": base64_message,
# "date": curr_date}
# message = json.dumps(message_format)
publisher.sender(message)
# print(f)
print("send message to sender function")
# time.sleep(0.1)
# os.remove(f)
else:
print("VISA")
wb1.delete_cols(3)
sheet = wb1
clist = []
# card = wb1.cell(row=2, column=1)
# s = str(card.value).split(",")[1].split(" ")[3]
# card_re = str(re.findall(r'[0-9]{4}',s))
b3 = sheet.cell(row=2, column=1)
s = str(b3.value).split(",")[1].split(" ")[3]
print(s)
r = re.compile('[0-9]{4}')
# print(r)
newlist = list(s)
# rint(newlist)
list1 = [newlist, 2]
if newlist != []:
clist.append(', '.join(newlist)) # add cards number to list
wbb = Workbook()
ws = wbb.active
x = ['תאריך עסקה', 'שם בית העסק', 'סכום עסקה', 'קטגוריה', 'מספר כרטיס']
counter = 1
for i in x:
ws.cell(row=1, column=counter, value=i)
counter += 1
for i in range(4, mr):
for j in range(1, 4):
c = wb1.cell(row=i, column=j)
ws.cell(row=i - 2, column=j).value = c.value
ws.cell(row=i - 2, column=5).value = s
f = 'c:\\OM\\output-visa-' + str(uuid.uuid4()) + '.xlsx'
wbb.save(filename=f)
with open(f, 'rb') as binary_file:
binary_file_data = binary_file.read()
base64_encoded_data = base64.b64encode(binary_file_data)
base64_message = base64_encoded_data.decode('utf-8')
print("Before publish to yogev")
# message_format = {"userid": userId, "time": curr_date, "base64buffer": base64_message,
# "date": curr_date}
# message = json.dumps(message_format)
publisher.sender(message)
except:
print('cannot parsing xlsx file, the file is corrupted')
if str(file_extension).split(".")[1] == 'xlsx':
print('excel format : xlsx')
try:
xls_filelike = io.BytesIO(decoded_data)
workbook = openpyxl.load_workbook(xls_filelike)
wbb2 = Workbook()
ws = wbb2.active
data = workbook
# parser.read_file(data)
f2 = 'c:\\OM\\output-xlsx-' + str(uuid.uuid4()) + '.xlsx'
workbook.save(filename=f2)
workbook = openpyxl.load_workbook(f2)
#wb = load_workbook(workbook)
wb1 = workbook.active
mr = wb1.max_row
mc = wb1.max_column
match = wb1.cell(row=1, column=1)
if match.value==None:
print("ISRACARD")
wb1.delete_cols(3, 2)
sheet = wb1
alist = []
blist = []
wbb = Workbook()
ws = wbb.active
x = ['תאריך עסקה', 'שם בית העסק', 'סכום עסקה', 'קטגוריה', 'מספר כרטיס']
counter = 1
for i in x:
ws.cell(row=1, column=counter, value=i)
counter += 1
for i in range(4, mr):
b3 = sheet.cell(row=i, column=1)
s = str(b3.value).split(" ")
r = re.compile('[0-9]{4}')
newlist = list(filter(r.match, s))
list1 = [newlist, i]
if newlist != []:
alist.append(i) # add row number for cars number to list
blist.append(', '.join(newlist)) # add cards number to list
else:
continue
alist.append(mr + 5)
for a in range(0, len(alist) - 1):
for i in range(alist[a] + 3, alist[a + 1] - 2):
for j in range(1, 4):
# reading cell value from source excel file
c = wb1.cell(row=i, column=j)
# writing the read value to destination excel file
ws.cell(row=i - 5, column=j).value = c.value
ws.cell(row=i - 5, column=5).value = str(blist[a])
for j in range(1, 4):
for i in range(1, mr):
if ws.cell(row=i, column=1).value is None:
ws.delete_rows(i)
else:
continue
f = 'c:\\OM\\output-isracard' + str(uuid.uuid4())+'.xlsx'
wbb.save(filename=f)
#channel.queue_declare(queue='Yogevhello', durable=True)
with open(f, 'rb') as binary_file:
# print(binary_file)
binary_file_data = binary_file.read()
base64_encoded_data = base64.b64encode(binary_file_data)
base64_message = base64_encoded_data.decode('utf-8')
print("Before publish to yogev")
#wwc = {"userid": "Eldar", "time": "10/04/2020", "base64buffer": base64_message}
# message_format = {"userid": userId, "time": curr_date, "base64buffer": base64_message, "date": curr_date}
# message = json.dumps(message_format)
publisher.sender(message)
#print(f)
#print("send message to sender function")
# time.sleep(0.1)
# os.remove(f)
else:
print("VISA")
wb1.delete_cols(3)
sheet = wb1
clist = []
# card = wb1.cell(row=2, column=1)
# s = str(card.value).split(",")[1].split(" ")[3]
# card_re = str(re.findall(r'[0-9]{4}',s))
b3 = sheet.cell(row=2, column=1)
s = str(b3.value).split(",")[1].split(" ")[3]
print(s)
r = re.compile('[0-9]{4}')
#print(r)
newlist = list(s)
#rint(newlist)
list1 = [newlist, 2]
if newlist != []:
clist.append(', '.join(newlist)) # add cards number to list
wbb = Workbook()
ws = wbb.active
x = ['תאריך עסקה', 'שם בית העסק', 'סכום עסקה', 'קטגוריה', 'מספר כרטיס']
counter = 1
for i in x:
ws.cell(row=1, column=counter, value=i)
counter+=1
for i in range(4,mr):
for j in range(1,4):
c = wb1.cell(row=i, column=j)
ws.cell(row=i - 2, column=j).value = c.value
ws.cell(row=i - 2, column=5).value = s
f = 'c:\\OM\\output-visa-' + str(uuid.uuid4()) + '.xlsx'
wbb.save(filename=f)
with open(f, 'rb') as binary_file:
binary_file_data = binary_file.read()
base64_encoded_data = base64.b64encode(binary_file_data)
base64_message = base64_encoded_data.decode('utf-8')
print("Before publish to yogev")
# message_format = {"userid": userId, "time": curr_date, "base64buffer": base64_message, "date": curr_date}
# message = json.dumps(message_format)
publisher.sender(message)
except:
print('cannot parsing xlsx file, the file is corrupted')
else:
print('Cannot parsing json from rabbit')
# channel.basic_consume(
# queue='userDataToProcess', on_message_callback=callback, auto_ack=True)
#
# print(' [*] Waiting for messages. To exit press CTRL+C')
#
# channel.start_consuming()
while(True):
try:
print("Connecting...")
channel.basic_consume(
queue='userDataToProcess', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.stop_consuming()
connection.close()
continue
except pika.exceptions.ConnectionClosedByBroker:
# Uncomment this to make the example not attempt recovery
# from server-initiated connection closure, including
# when the node is stopped cleanly
#
# break
continue
# Do not recover on channel errors
except pika.exceptions.AMQPChannelError as err:
print("Caught a channel error: {}, stopping...".format(err))
channel.stop_consuming()
connection.close()
continue
#Recover on all other connection errors
except pika.exceptions.AMQPConnectionError:
print("Connection was closed, retrying...")
# channel.start_consuming()
continue