show me the code, 上碼!
import com.alibaba.excel.annotation.ExcelProperty;
import com.example.demo.vo.Student;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* 通過反射實現判斷excel的單元格內容不爲空
*
* @author myssen
* @date 2021/6/17 9:22
*/
public class Test0617 {
public static void main(String[] args) throws UnsupportedEncodingException {
List<Student> list = new ArrayList<>();
Student student = new Student();
student.setName("劉備");
student.setSex("男");
student.setAge(10);
list.add(student);
Student student2 = new Student();
student2.setName("關羽");
student2.setSex("男");
student2.setAge(10);
list.add(student2);
for (Student row : list) {
try {
String message = checkNotBlank(row);
if (!"".equals(message)) {
System.out.println("錯誤提示:" + message);
}else{
// doSomething
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
/**
* excel必填字段不爲空檢查
*
* @param row
* @return
* @throws Exception
*/
public static String checkNotBlank(Student row) throws Exception {
Field[] fields = Student.class.getDeclaredFields();
String message = "";
for (Field field : fields) {
PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), Student.class);
Method getMethod = descriptor.getReadMethod();
String value = getMethod.invoke(row).toString();
Annotation[] annotations = field.getAnnotations();
boolean flagNull = false;
for (Annotation annotation : annotations) {
if (annotation.annotationType().equals(ExcelProperty.class)) {
String columnName = ((ExcelProperty) annotation).value()[0];
if (columnName.contains("必填")) {
if (value == null || "".equals(value)) {
message = columnName;
flagNull = true;
break;
}
}
}
}
if (flagNull) {
break;
}
}
return message;
}
}
此文結束