爷的眼睛闪亮
insideDotNet En_summerGarden

定义实体类

首先定义实体类User,需要继承BaseRowModel

@Data
public class User extends BaseRowModel {
    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "昵称", index = 1)
    private String nickName;

    @ExcelProperty(value = "密码", index = 2)
    private String password;

    //不支持LocalDate
    @ExcelProperty(value = "生日", index = 3, format = "yyyy/MM/dd")
    private Date birthday;
}

日期类型不支持LocalDate,只能是Date

数据读取监听类

  • 继承AnalysisEventListener并要求泛型类是BaseRowModel的子类
@Slf4j
public class ExcelListener<T extends BaseRowModel> extends AnalysisEventListener<T> {
    private final List<T> rows = new ArrayList<>();

    @Override
    public void invoke(T object, AnalysisContext context) {
        rows.add(object);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("read {} rows %n", rows.size());
    }

    public List<T> getRows() {
        return rows;
    }
}

实现的比较直接,就是全部读取到List后再处理

Excel读写工具类

实现Excel数据的读取和写入

@Slf4j
public final class ExcelUtil {
    /**
     * 从Excel中读取文件,读取的文件是一个DTO类,该类必须继承BaseRowModel
     * 具体实例参考 : MemberMarketDto.java
     * 参考:https://github.com/alibaba/easyexcel
     * 字符流必须支持标记,FileInputStream 不支持标记,可以使用BufferedInputStream 代替
     * BufferedInputStream bis = new BufferedInputStream(new FileInputStream(...));
     */
    public static <T extends BaseRowModel> List<T> readExcel(final InputStream inputStream, final Class<? extends BaseRowModel> clazz) {
        if (null == inputStream) {
            throw new NullPointerException("the inputStream is null!");
        }
        ExcelListener<T> listener = new ExcelListener<>();
        // 这里因为EasyExcel-1.1.1版本的bug,所以需要选用下面这个标记已经过期的版本
        ExcelReader reader = new ExcelReader(inputStream,  valueOf(inputStream), null, listener);
        reader.read(new com.alibaba.excel.metadata.Sheet(1, 1, clazz));

        return listener.getRows();
    }


    public static void writeExcel(final File file, List<? extends BaseRowModel> list) {
        try (OutputStream out = new FileOutputStream(file)) {
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
            //写第一个sheet,  有模型映射关系
            Class<? extends BaseRowModel> t = list.get(0).getClass();
            Sheet sheet = new Sheet(1, 0, t);
            writer.write(list, sheet);
            writer.finish();
        } catch (IOException e) {
            log.warn("fail to write to excel file: file[{}]", file.getName(), e);
        }
    }


    /**
     * 根据输入流,判断为xls还是xlsx,该方法原本存在于easyexcel 1.1.0 的ExcelTypeEnum中。
     */
    public static ExcelTypeEnum valueOf(InputStream inputStream) {
        try {
            FileMagic fileMagic = FileMagic.valueOf(inputStream);
            if (FileMagic.OLE2.equals(fileMagic)) {
                return ExcelTypeEnum.XLS;
            }
            if (FileMagic.OOXML.equals(fileMagic)) {
                return ExcelTypeEnum.XLSX;
            }
            throw new IllegalArgumentException("excelTypeEnum can not null");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

实用类

public class EasyexcelApplication {
    public static void main(String[] args) {
        try (FileInputStream inputStream = new FileInputStream("user.xlsx")) {
            List<User> users = ExcelUtil.readExcel(new BufferedInputStream(inputStream), User.class);
            System.out.println(users);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意事项

  • 日期类型只支持Date,不支持LocalDate和LocalDateTime

常见错误

  • NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file:这个是1.1.1的bug,在1.1.2-beta2中已经处理,暂时解决的办法就是使用过期的方法
new ExcelReader(inputStream,  ExcelTypeEnum.XLSX, null, listener)
  • java.io.IOException: getFileMagic() only operates on streams which support mark(int):因为FileInputStream不支持标记,可以使用BufferedInputStream代替
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(...));

转自链接:https://www.jianshu.com/p/80505fb72493

posted on 2021-08-20 11:26  爷的眼睛闪亮  阅读(1139)  评论(0编辑  收藏  举报