工具类代码:
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
public class ReadExcel {
/**
* read the Excel file
*
* @param file the Excel file
* @param cls the Target class
* @param
* @return
*/
public List readExcel(MultipartFile file, Class cls) {
String postfix = Postfix.getPostfix(file.getOriginalFilename());
if (CommonPath.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
return readXls(file, cls);
} else if (CommonPath.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
return readXlsx(file, cls);
}
return null;
}
/**
* Read the Excel 2003 - 2007
*
* @param file the excel file
* @param cls the target class
* @return
*/
public List readXls(MultipartFile file, Class cls) {
log.debug("正在读入" + file.getOriginalFilename());
List dataList = new ArrayList<>();
HSSFWorkbook workbook = null;
InputStream is = null;
try {
is = file.getInputStream();
workbook = new HSSFWorkbook(is);
if (workbook != null) {
//类映射
Map> classMap = new HashMap<>();
Field[] fields = cls.getDeclaredFields();
//获取所有的属性
for (Field field : fields) {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
String value = annotation.value();
if (!classMap.containsKey(value)) {
classMap.put(value, new ArrayList<>());
}
field.setAccessible(true);
classMap.get(value).add(field);
}
}
Map> reflectionMap = new HashMap<>();
Sheet sheet = workbook.getSheetAt(0);
AtomicInteger ai = new AtomicInteger();
sheet.forEach(row -> {
int i = ai.incrementAndGet();
AtomicInteger aj = new AtomicInteger();
if (i == 1) {//首行 提取注解
row.forEach(cell -> {
int j = aj.incrementAndGet();
String cellValue = getCellValue(cell);
if (classMap.containsKey(cellValue)) {
reflectionMap.put(j, classMap.get(cellValue));
}
});
} else {
try {
T t = cls.newInstance();
row.forEach(cell -> {
int j = aj.incrementAndGet();
if (reflectionMap.containsKey(j)) {
String cellValue = getCellValue(cell);
List fieldList = reflectionMap.get(j);
for (Field field : fieldList) {
try {
field.set(t, cellValue);
} catch (Exception e) {
//
}
}
}
});
dataList.add(t);
} catch (Exception e) {
}
}
});
}
} catch (Exception e) {
}
finally {
if (workbook != null) {
try {
is.close();
} catch (Exception e) {
log.debug("文件流为正确关闭");
}
}
}
return dataList;
}
/**
* Read the Excel 2010
*
* @param file the excel file
* @param cls the target class
* @return
*/
public List readXlsx(MultipartFile file, Class cls) {
log.debug("正在读入" + file.getOriginalFilename());
List dataList = new ArrayList<>();
XSSFWorkbook workbook = null;
InputStream is = null;
try {
is = file.getInputStream();
workbook = new XSSFWorkbook(is);
if (workbook != null) {
//类映射
Map> classMap = new HashMap<>();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
String value = annotation.value();
if (!classMap.containsKey(value)) {
classMap.put(value, new ArrayList<>());
}
field.setAccessible(true);
classMap.get(value).add(field);
}
}
Map> reflectionMap = new HashMap<>();
Sheet sheet = workbook.getSheetAt(0);
AtomicInteger ai = new AtomicInteger();
sheet.forEach(row -> {
int i = ai.incrementAndGet();
AtomicInteger aj = new AtomicInteger();
if (i == 1) {//首行 提取注解
row.forEach(cell -> {
int j = aj.incrementAndGet();
String cellValue = getCellValue(cell);
if (classMap.containsKey(cellValue)) {
reflectionMap.put(j, classMap.get(cellValue));
}
});
} else {
try {
T t = cls.newInstance();
row.forEach(cell -> {
int j = aj.incrementAndGet();
if (reflectionMap.containsKey(j)) {
String cellValue = getCellValue(cell);
List fieldList = reflectionMap.get(j);
for (Field field : fieldList) {
try {
field.set(t, cellValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
dataList.add(t);
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
is.close();
} catch (Exception e) {
}
}
}
return dataList;
}
/**
* 获取excel 单元格数据
*
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue()).trim();
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue()).trim();
} else {
return String.valueOf(cell.getStringCellValue()).trim();
}
}
/**
* excel字段对应注解
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelColumn {
String value() default "";
}
}
还有两个类:
public class CommonPath {
/**
* 2010版本excel
*/
public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
/**
* 2003-2007版本excel
*/
public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
/**
* 判断是否为空
*/
public static final String EMPTY = "";
/**
* 以.分隔
*/
public static final String POINT = ".";
/**
* 不是excel文件判断
*/
public static final String NOT_EXCEL_FILE = " : Not the Excel file!";
/**
* 执行中
*/
public static final String PROCESSING = "Processing...";
}
还有一个:
public class Postfix {
public static String getPostfix(String path) {
if (path == null || CommonPath.EMPTY.equals(path.trim())) {
return CommonPath.EMPTY;
}
if (path.contains(CommonPath.POINT)) {
return path.substring(path.lastIndexOf(CommonPath.POINT) + 1, path.length());
}
return CommonPath.EMPTY;
}
}