注解+反射优雅的实现Excel导入导出(通用版)

实现过程:

首先需要创建三个注解

一个是EnableExport ,必须有这个注解才能导出

/**
 * 设置允许导出
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableExport {
     String fileName();

}

然后就是EnableExportField,有这个注解的字段才会导出到Excel里面,并且可以设置列宽

/**
 * 设置该字段允许导出
 * 并且可以设置宽度
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableExportField {
     int colWidth() default  100;
     String colName();
}

再就是ImportIndex,导入的时候设置Excel中的列对应的序号

/**
 * 导入时索引
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ImportIndex {
     int index() ;

}

注解使用示例

 三个注解创建好之后就需要开始操作Excel了

首先,导入方法。在后台接收到前端上传的Excel文件之后,使用poi来读取Excel文件

我们根据传入的类型上面的字段注解的顺序来分别为不同的字段赋值,然后存入集合中,再返回

代码如下:

/**
 * 将Excel转换为对象集合
 * @param excel Excel 文件
 * @param clazz pojo类型
 * @return
 */
public static List<Object> parseExcelToList(File excel,Class clazz){
    List<Object> res = new ArrayList<>();
    // 创建输入流,读取Excel
    InputStream is = null;
    Sheet sheet = null;
    try {
        is = new FileInputStream(excel.getAbsolutePath());
        if (is != null) {
            Workbook workbook = WorkbookFactory.create(is);
            //默认只获取第一个工作表
            sheet = workbook.getSheetAt(0);
            if (sheet != null) {
             //前两行是标题
                int i = 2;
                String values[] ;
                Row row = sheet.getRow(i);
                while (row != null) {
                    //获取单元格数目
                    int cellNum = row.getPhysicalNumberOfCells();
                    values = new String[cellNum];
                    for (int j = 0; j <= cellNum; j++) {
                        Cell cell =   row.getCell(j);
                        if (cell != null) {
                            //设置单元格内容类型
                            cell.setCellType(Cell.CELL_TYPE_STRING );
                            //获取单元格值
                            String value = cell.getStringCellValue() == null ? null : cell.getStringCellValue();
                            values[j]=value;
                        }
                    }
                    Field[] fields = clazz.getDeclaredFields();
                    Object obj = clazz.newInstance();
                    for(Field f : fields){
                        if(f.isAnnotationPresent(ImportIndex.class)){
                            ImportIndex annotation = f.getDeclaredAnnotation(ImportIndex.class);
                            int index = annotation.index();
                            f.setAccessible(true);
                            //此处使用了阿里巴巴的fastjson包里面的一个类型转换工具类
                            Object val =TypeUtils.cast(values[index],f.getType(),null);
                            f.set(obj,val);
                        }
                    }
                    res.add(obj);
                    i++;
                    row=sheet.getRow(i);
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}

https://mp.weixin.qq.com/s/OK5rzF1FY6E7UENjzeQUsQ

https://www.cnblogs.com/poi-Excel/p/15137585.html

故乡明
原文地址:https://www.cnblogs.com/luweiweicode/p/15060441.html