一、实现EasyExcel对Excel读操作

1、创建实体类

  1. import com.alibaba.excel.annotation.ExcelProperty;
  2. public class ReadData {
  3. //设置列对应的属性
  4. @ExcelProperty(index = 0)
  5. private int sid;
  6. //设置列对应的属性
  7. @ExcelProperty(index = 1)
  8. private String sname;
  9. public int getSid() {
  10. return sid;
  11. }
  12. public void setSid(int sid) {
  13. this.sid = sid;
  14. }
  15. public String getSname() {
  16. return sname;
  17. }
  18. public void setSname(String sname) {
  19. this.sname = sname;
  20. }
  21. @Override
  22. public String toString() {
  23. return "ReadData{" +
  24. "sid=" + sid +
  25. ", sname='" + sname + '\'' +
  26. '}';
  27. }
  28. }

2、创建读取操作的监听器

  1. import com.alibaba.excel.context.AnalysisContext;
  2. import com.alibaba.excel.event.AnalysisEventListener;
  3. import com.alibaba.excel.exception.ExcelDataConvertException;
  4. import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.Map;
  8. //创建读取excel监听器
  9. public class ExcelListener extends AnalysisEventListener<ReadData> {
  10. //创建list集合封装最终的数据
  11. List<ReadData> list = new ArrayList<ReadData>();
  12. //一行一行去读取excle内容
  13. @Override
  14. public void invoke(ReadData user, AnalysisContext analysisContext) {
  15. System.out.println("***"+user);
  16. list.add(user);
  17. }
  18. //读取excel表头信息
  19. @Override
  20. public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
  21. System.out.println("表头信息:"+headMap);
  22. }
  23. //读取完成后执行
  24. @Override
  25. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  26. }
  27. }

3、调用实现最终的读取

public static void main(String[] args) throws Exception {

     // 写法1:
     String fileName = "F:\\01.xlsx";
     // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
     EasyExcel.read(fileName, ReadData.class, new ExcelListener()).sheet().doRead();

     // 写法2:
     InputStream in = new BufferedInputStream(new FileInputStream("F:\\01.xlsx"));
     ExcelReader excelReader = EasyExcel.read(in, ReadData.class, new ExcelListener()).build();
     ReadSheet readSheet = EasyExcel.readSheet(0).build();
     excelReader.read(readSheet);
     // 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的
     excelReader.finish();
}