管道基础大数据平台系统开发-【后端】-Server
1
13693261870
2022-11-21 24a09196ed7c1ae7502dc64264469a2de03389aa
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
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.lf.server.helper;
 
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.lf.server.annotation.ExcelHead;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
/**
 * Excel帮助类
 * @author WWW
 */
public class ExcelHelper {
    /**
     * 读取Excel
     *
     * @param pathName 文件路径
     * @param <T>      泛型类
     * @return 泛型类集合
     */
    public static <T> List<T> readExcel(Class<?> clazz, String pathName) {
        ExcelHead head = getExcelHead(clazz);
        int headRowNumber = head == null ? 1 : head.headRows();
        String[] strs = null == head || StringHelper.isEmpty(head.excludeSheets()) ? null : head.excludeSheets().split(",");
        List<String> excludeSheets = null == strs ? null : Arrays.asList(strs);
 
        List<T> list = new ArrayList<T>();
        ExcelReader reader = EasyExcel.read(pathName, clazz, new AnalysisEventListener<T>() {
            @Override
            public void invoke(T t, AnalysisContext context) {
                list.add(t);
            }
 
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                //
            }
        }).headRowNumber(headRowNumber).build();
 
        List<ReadSheet> sheets = reader.excelExecutor().sheetList();
        for (ReadSheet sheet : sheets) {
            if (strs != null && excludeSheets.contains(sheet.getSheetName())) {
                continue;
            }
 
            reader.read(sheet);
        }
 
        return list;
    }
 
    /**
     * 获取Excel头注解类
     *
     * @param clazz Class
     * @param <T>   泛型类
     * @return 头行数
     */
    public static <T> ExcelHead getExcelHead(Class<?> clazz) {
        ExcelHead head = clazz.getAnnotation(ExcelHead.class);
        if (head != null) {
            return head;
        }
 
        return null;
    }
}