快速上手
- 自定义注解
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcelDropdown {
String[] value() default {};
boolean isAllowOtherValue() default false;
}
- 添加工具类
@Data
@Accessors(chain = true)
@ToString
public class AnnotationUtil<T> {
public Class<T> clazz;
public AnnotationUtil(Class<T> clazz) {
this.clazz = clazz;
}
public AnnotationUtil updateAnnoAttrValue(String fieldName, Class<? extends Annotation> annotationClass, String attrName, Object attrValue) throws Exception {
Field[] declaredFields = this.clazz.getDeclaredFields();
if (null != declaredFields && declaredFields.length != 0) {
for (int i = 0; i < declaredFields.length; i++) {
Field declaredField = declaredFields[i];
if (fieldName.equals(declaredField.getName())) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(declaredField.getAnnotation(annotationClass));
Field hField = invocationHandler.getClass().getDeclaredField("memberValues");
hField.setAccessible(true);
Map memberValues = (Map) hField.get(invocationHandler);
memberValues.put(attrName, attrValue);
break;
}
}
}
return this;
}
public AnnotationUtil updateAnnoAttrValue(String[] fieldNames, Class<? extends Annotation> annotationClass, String[] attrNames, Object[] attrValues) throws Exception {
Field[] declaredFields = this.clazz.getDeclaredFields();
if (null != declaredFields && declaredFields.length != 0) {
HashMap<String, Field> map = new HashMap<>();
for (int i = 0; i < declaredFields.length; i++) {
Field declaredField = declaredFields[i];
map.put(declaredField.getName(), declaredField);
}
for (int j = 0; j < fieldNames.length; j++) {
if (!map.containsKey(fieldNames[j])) {
throw new Exception("字段名错误");
}
if(map.get(fieldNames[j]).getAnnotation(annotationClass) == null){
throw new Exception("该属性上无此注解");
}
InvocationHandler invocationHandler = Proxy.getInvocationHandler(map.get(fieldNames[j]).getAnnotation(annotationClass));
Field hField = invocationHandler.getClass().getDeclaredField("memberValues");
hField.setAccessible(true);
Map memberValues = (Map) hField.get(invocationHandler);
memberValues.put(attrNames[j], attrValues[j]);
}
}
return this;
}
}
- 调用下面这两个方法
public void setExcelDropdownValue(String[] fieldNames, Object[] attrValues) throws Exception {
AnnotationUtil<T> s = new AnnotationUtil<T>(this.clazz);
String[] attrNames = new String[fieldNames.length];
for (int i = 0; i < attrNames.length; i++) {
attrNames[i] = "value";
}
s.updateAnnoAttrValue(fieldNames, ExcelDropdown.class, attrNames, attrValues);
}
public void downLoad(HttpServletResponse res, List<T> data, String fileName, String sheetName) throws Exception {
setMapDropDown(this.clazz);
DropdownWriteHandler dropdownWriteHandler = new DropdownWriteHandler();
EasyExcelFactory.write(getOutputStream(fileName, res), this.clazz).sheet(sheetName).registerWriteHandler(dropdownWriteHandler).doWrite(data);
}
读写基本数据参考 EasyExcel官网