forked from mkesicki/excel_validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
excel_validator.py
248 lines (193 loc) · 7.59 KB
/
excel_validator.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
#!/usr/bin/python -u
# -*- coding: UTF-8 -*-
import argparse
import os.path
import sys
import time
import yaml
from openpyxl.reader.excel import load_workbook
from openpyxl.styles import PatternFill
from openpyxl.utils import column_index_from_string, get_column_letter
from progress.bar import Bar
from validator import *
def isValid(settings, value, coordinate, errors, value2 = None):
#validator list
classmap = {
'NotBlank': NotBlankValidator.NotBlankValidator,
'Type': TypeValidator.TypeValidator,
'Length': LengthValidator.LengthValidator,
'Regex': RegexValidator.RegexValidator,
'Email': EmailValidator.EmailValidator,
'Choice': ChoiceValidator.ChoiceValidator,
'Date': DateTimeValidator.DateTimeValidator,
'ExcelDate': ExcelDateValidator.ExcelDateValidator,
'Country': CountryValidator.CountryValidator,
'Conditional': ConditionalValidator.ConditionalValidator
}
violations = []
type = settings.keys()[0]
data = settings.values()[0]
validator = classmap[type](data)
if type != 'Conditional':
result = validator.validate(value)
else:
result = validator.validate(value, value2)
if (result == False):
violations.append(validator.getMessage())
if len(violations) > 0:
errors.append((coordinate, violations))
return True
def setSettings(config):
settings = {}
excludes = []
print "Get validation config " + config
try:
stream = file(config, 'r')
except IOError, e:
print e
exit(1)
config = yaml.load(stream)
if 'validators' in config and 'columns' in config.get('validators'):
settings['validators'] = config.get('validators').get('columns')
else:
return False
if 'default' in config.get('validators') :
settings['defaultValidator'] = config.get('validators').get('default')[0]
else:
settings['defaultValidator'] = None
if 'excludes' in config:
for column in config.get('excludes'):
excludes.append(column_index_from_string(column))
settings['excludes'] = excludes
else:
settings['excludes'] = []
if 'range' in config:
settings['range'] = config.get('range')[0] + "1:" + config.get('range')[1]
else:
settings['range'] = None
if 'header' in config:
settings['header'] = config.get('header')
else:
settings['header'] = True
return settings
def markErrors(errors, excelFile, sheetName, tmpDir, printErrors = False):
progressBar = Bar('Processing', max = len(errors))
if os.path.getsize(excelFile) > 10485760:
print "Log broken cells"
for error in errors:
progressBar.next()
if printErrors.lower() == "true":
print "Broken Excel cell: " + error[0] + " [ "+ ','.join(error[1]) + " ]"
else:
print "Broken Excel cell: " + error[0]
progressBar.finish();
return
#open Excel file
newFile = os.path.join(tmpDir , "errors_" + time.strftime("%Y-%m-%d") + "_" + str(int(time.time())) + "_" + os.path.basename(excelFile))
fileName,fileExtension = os.path.splitext(excelFile)
if fileExtension == '.xlsm':
wb = load_workbook(excelFile, keep_vba=True, data_only=True)
else:
wb = load_workbook(excelFile, data_only=True)
creator = wb.properties.creator
ws = wb.get_sheet_by_name(sheetName)
redFill = PatternFill(start_color='FFFF0000',
end_color = 'FFFF0000',
fill_type = 'solid')
for error in errors:
progressBar.next()
print "Broken Excel cell: " + error[0]
cell = ws[error[0]]
if printErrors:
cell.value = ','.join(error[1])
cell.fill = redFill
progressBar.finish()
#save error excel file
wb.properties.creator = creator
print "[[Save file: " + newFile + "]]"
try:
wb.save(newFile)
except Exception, e:
print e
exit(1)
return newFile
def validate(settings, excelFile, sheetName, tmpDir, printErrors = False):
print "Validate Excel Sheet " + sheetName
errors = []
#open Excel file
print "Parse Excel file"
wb = load_workbook(excelFile, keep_vba=True, data_only=True, read_only=True)
ws = wb.get_sheet_by_name(sheetName)
progressBar = Bar('Processing', max=ws.max_row)
if 'range' in settings and settings['range'] != None:
settings['range'] = settings['range'] + (str)(ws.max_row)
#iterate excel sheet
rowCounter = 0
for row in ws.iter_rows(settings['range']):
progressBar.next()
columnCounter = 0
rowCounter = rowCounter + 1
#do not parse empty rows
if isEmpty(row):
continue
for cell in row:
columnCounter = columnCounter + 1
try:
value = cell.value
except ValueError:
#case when it is not possible to read value at all from any reason
column = get_column_letter(columnCounter)
coordinates = "%s%d" % (column, rowCounter)
errors.append((coordinates, ValueError))
#find header (first) row
if settings['header'] != True:
if value == settings['header']:
settings['header'] = True
break
#skip excludes column
if hasattr(cell, 'column') and cell.column in settings['excludes']:
continue
column = get_column_letter(columnCounter)
coordinates = "%s%d" % (column, rowCounter)
if column in settings['validators']:
for type in settings['validators'][column]:
name = type.keys()[0]
if name != 'Conditional':
isValid(type, value, coordinates, errors)
else:
fieldB = type.values()[0]['fieldB']
value2 = ws[fieldB + str(rowCounter)].value
isValid(type, value, coordinates, errors, value2)
elif settings['defaultValidator'] != None:
isValid(settings['defaultValidator'], value, coordinates, errors)
progressBar.finish()
print "Found %d error(s)" % len(errors)
if (len(errors) > 0):
return markErrors(errors, excelFile, sheetName, tmpDir, printErrors)
return True
def isEmpty(row):
for cell in row:
if cell.value:
return False
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'Mark validation errors in Excel sheet.')
parser.add_argument('config', metavar = 'config', help = 'Path to YAML config file')
parser.add_argument('file', metavar = 'file', help = 'Path to excel sheet file')
parser.add_argument('sheetName', metavar = 'sheetName', help = 'Excel Sheet Name')
parser.add_argument('tmpDir', metavar = 'tmpDir', help = 'Temporary directory path')
parser.add_argument('--errors', metavar = 'errors', help = 'Print errors messages in cells marked as invalid')
args = parser.parse_args()
settings = setSettings(args.config)
if settings == False:
sys.exit("Incorrect config file " + args.config)
try:
results = validate(settings, args.file, args.sheetName, args.tmpDir, args.errors)
except Exception, e:
sys.exit("Error occured: " + e.message)
if results != True:
if results:
sys.exit("Validation errors store in: [[" + results + "]]")
else:
sys.exit("Invalid file is too big to generate annotated Excel file")
sys.exit(0)