基于反射导出excel工具类

controller

@RequestMapping(“exportUserExcel”)
@ResponseBody
public ResponseServer exportUserExcel(UserParameter userParameter) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
List userList=userService.exportUserExcel(userParameter);

    if (userList.size()==0){
        return ResponseServer.error(ServerEnum.EXPORT_NULL);
    }
    String url= ExportExcelUtils.export(userList,UserExcel.class);
    return ResponseServer.success("commons/"+url);

}

工具类

public class ExportExcelUtils {

//我支持任何一个类
public static String export(List data,Class clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //title,column,mkdir,sheetName,columnName
    ExcelBean excelBean=new ExcelBean();
    //用到java的反射机制获取注解
    ExcelAnnotation excelAnnotation= (ExcelAnnotation) clazz.getAnnotation(ExcelAnnotation.class);
    if(excelAnnotation != null){
        excelBean.setTitle(excelAnnotation.title());
        excelBean.setMkdir(excelAnnotation.mkdir());
        excelBean.setSheetName(excelAnnotation.sheetName());
        //获取字段和字段对应的名称
        List columnList=new ArrayList();
        List columnNameList=new ArrayList();
        //获取类中的所有属性
        Field[] declaredFields = clazz.getDeclaredFields();
        for(int i=0;i

}

注解类

@Documented
@Target({ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAnnotation {

String title() default "";
String columnName() default "";
String sheetName() default "";
String mkdir() default "";

}

你可能感兴趣的:(spring)