引入依赖
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.1.5</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.22</version> </dependency>
|
实现过程
定义监听器
定义一个监听器继承 AnalysisEventListener 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.Data; import lombok.EqualsAndHashCode;
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
@Data @EqualsAndHashCode(callSuper = true) public class ExcelListener extends AnalysisEventListener<Object> {
private List<JSONObject> dataList = new ArrayList<>();
private Map<String, Integer> importHeads = new HashMap<>(16);
@Override public void invoke(Object data, AnalysisContext context) { String headStr = JSON.toJSONString(data); dataList.add(JSONObject.parseObject(headStr)); }
@Override public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) { for (Integer key : headMap.keySet()) { if (importHeads.containsKey(headMap.get(key))) { continue; } importHeads.put(headMap.get(key), key); } }
@Override public void doAfterAllAnalysed(AnalysisContext context) {
} }
|
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import com.alibaba.excel.EasyExcel; import com.alibaba.fastjson.JSONObject;
import java.util.List; import java.util.Map;
public class Test {
public static void main(String[] args) { String fileName = "C:\\Users\\LeDao\\Desktop\\测试.xlsx"; ExcelListener excelListener = new ExcelListener(); EasyExcel.read(fileName, excelListener).sheet().doRead(); Map<String, Integer> heads = excelListener.getImportHeads(); System.out.println(heads); List<JSONObject> dataList = excelListener.getDataList(); for (JSONObject jsonObject : dataList) { System.out.println(jsonObject); } } }
|
结果
表格数据
读取的结果
PS.
上面是直接读取电脑磁盘上的 Excel 表,也可以读取前端上传的 Excel 表
1 2 3 4 5 6 7 8 9 10
| @PostMapping("upload") @ResponseBody public String upload(MultipartFile file) throws IOException { ExcelListener excelListener = new ExcelListener(); EasyExcel.read(file.getInputStream(), excelListener).sheet().doRead(); Map<String, Integer> heads = excelListener.getImportHeads(); List<JSONObject> dataList = excelListener.getDataList(); }
|