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;
|
}
|
}
|