-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathExcelValidationUtils.java
More file actions
191 lines (161 loc) · 5.89 KB
/
ExcelValidationUtils.java
File metadata and controls
191 lines (161 loc) · 5.89 KB
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
package cn.idev.excel.util;
import cn.idev.excel.annotation.validation.ExcelRequired;
import cn.idev.excel.annotation.ExcelProperty;
import cn.idev.excel.annotation.ExcelIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* Excel validation utility class.
* Provides common methods for Excel data validation.
*
* <p>This utility class offers batch validation capabilities for Excel data,
* particularly useful for validating required fields during data import operations.</p>
*
* <p>Example usage:</p>
* <pre>
* {@code
* List<ValidationResult> results = ExcelValidationUtils.validateRequiredBatch(dataList);
* if (!results.isEmpty()) {
* // Handle validation errors
* for (ValidationResult result : results) {
* System.out.println("Row " + (result.getRowIndex() + 1) + ": " +
* String.join(", ", result.getErrors()));
* }
* }
* }
* </pre>
*
* @author FastExcel Team
* @since 1.2.1
*/
public class ExcelValidationUtils {
private static final Logger logger = LoggerFactory.getLogger(ExcelValidationUtils.class);
/**
* Validates required fields of an object.
*
* @param obj the object to validate
* @return list of validation errors, empty if validation passes
*/
public static List<String> validateRequired(Object obj) {
List<String> errors = new ArrayList<>();
if (obj == null) {
errors.add("Validation object cannot be null");
return errors;
}
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// 跳过被@ExcelIgnore标记的字段
if (field.isAnnotationPresent(ExcelIgnore.class)) {
continue;
}
// 检查是否有@ExcelProperty注解(确定是Excel列)
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty == null) {
continue;
}
// 检查是否有@ExcelRequired注解
ExcelRequired excelRequired = field.getAnnotation(ExcelRequired.class);
if (excelRequired == null) {
continue;
}
try {
field.setAccessible(true);
Object value = field.get(obj);
// Check if field value is empty
if (isEmpty(value)) {
String fieldName = getFieldDisplayName(field, excelProperty);
String errorMessage = String.format("[%s] %s", fieldName, excelRequired.message());
errors.add(errorMessage);
logger.debug("Required field validation failed: {}", errorMessage);
}
} catch (IllegalAccessException e) {
logger.error("Failed to access field: {}", field.getName(), e);
errors.add(String.format("Failed to access field %s", field.getName()));
}
}
return errors;
}
/**
* Batch validates required fields for a list of objects.
*
* @param objList the list of objects to validate
* @return validation results, with row index (0-based) and error messages
*/
public static List<ValidationResult> validateRequiredBatch(List<?> objList) {
List<ValidationResult> results = new ArrayList<>();
if (objList == null || objList.isEmpty()) {
return results;
}
for (int i = 0; i < objList.size(); i++) {
Object obj = objList.get(i);
List<String> errors = validateRequired(obj);
if (!errors.isEmpty()) {
ValidationResult result = new ValidationResult();
result.setRowIndex(i);
result.setErrors(errors);
results.add(result);
}
}
return results;
}
/**
* Checks if a value is empty.
*
* @param value the value to check
* @return true if the value is empty, false otherwise
*/
private static boolean isEmpty(Object value) {
if (value == null) {
return true;
}
if (value instanceof String) {
return ((String) value).trim().isEmpty();
}
if (value instanceof Number) {
return false; // Numbers are not considered empty
}
return false;
}
/**
* Gets the display name of a field.
*
* @param field the field
* @param excelProperty the ExcelProperty annotation
* @return the display name for the field
*/
private static String getFieldDisplayName(Field field, ExcelProperty excelProperty) {
String[] values = excelProperty.value();
if (values.length > 0 && !values[0].isEmpty()) {
// Use the last value as display name
return values[values.length - 1];
}
return field.getName();
}
/**
* Validation result class that holds validation errors for a specific row.
*/
public static class ValidationResult {
private int rowIndex;
private List<String> errors;
public int getRowIndex() {
return rowIndex;
}
public void setRowIndex(int rowIndex) {
this.rowIndex = rowIndex;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
@Override
public String toString() {
return String.format("第%d行: %s", rowIndex + 1, String.join(", ", errors));
}
}
}