目录
DefaultExcelImportFieldFormat默认的数据转换接口
Excel导入的工具有很多,比如hutool的ExcelUtil,hutool-5.6.x支持poi-ooxml
版本高于 5.0.0
,但是由于当前项目本身依赖的poi版本低(3.10.FINAL),且无法进行升级(不要问为什么),只能通过重新造轮子,设计自己的Excel导入工具。
本文介绍ExcelImportUtils通过解析Bean中属性的ExcelImportField注解,读取Excel中的数据,通过反射对Bean中的属性进行设置数据。
版本依赖
- hutool-all 5.6.1
- poi 3.12
- poi-ooxml 3.10.FINAL
ExcelImportField注解
ExcelImportField添加在Bean的属性上,通过excel中列的下标进行对应。
- index: excel中列的索引下标,默认从0开始
- format: 数据转换类,默认DefaultExcelImportFieldFormat 不做任何处理,做具体的数据转换需要自己实现相应的转换类。
import java.lang.annotation.*;
/**
* @author xuyh0817
* @version 1.0.0
* @email xuyh0817@foxmail.com
* @date 2024/5/16 14:51
*
* @description excel导入标识
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelImportField {
/**
* excel下标 从0开始
*/
int index() default -1;
/**
* 数据转换类
*/
Class<? extends ExcelImportFieldFormat<?>> format() default DefaultExcelImportFieldFormat.class;
}
ExcelImportFieldFormat数据转换接口
/**
* @author xuyh0817
* @version 1.0.0
* @email xuyh0817@foxmail.com
* @date 2024/5/16 16:25
*
* @description 数据转换接口
*/
public interface ExcelImportFieldFormat<T> {
T format(String field);
}
DefaultExcelImportFieldFormat默认的数据转换接口
DefaultExcelImportFieldFormat是一个空类,没有做任何数据处理,做具体的数据转换需要自己实现相应的转换类或继承DefaultExcelImportFieldFormat重写format方法。
/**
* @author xuyh0817
* @version 1.0.0
* @email xuyh0817@foxmail.com
* @date 2024/5/20 10:39
*
* @description 默认处理方法,不做任何处理
*/
public class DefaultExcelImportFieldFormat implements ExcelImportFieldFormat<String>{
@Override
public String format(String field) {
return field;
}
}
ExcelImportUtils数据导入工具类
- 通过静态方法getInstance获取对象实例
- 通过imporData方法进行数据导入
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.*;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author xuyh0817
* @version 1.0.0
* @email xuyh0817@foxmail.com
* @date 2024/5/16 14:52
* @description 数据导入工具类
*/
@Slf4j
public class ExcelImportUtils {
/**
* 格式转换类集合
*/
private final static Map<String, ExcelImportFieldFormat<?>> FORMAT_MAP = new HashMap<>();
/**
* XLSX文件类型
*/
private final static String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/**
* XLS文件类型
*/
private final static String XLS = "application/vnd.ms-excel";
/**
* 获取实例对象
*
* @return ExcelImportUtils
*/
public static ExcelImportUtils getInstance() {
return new ExcelImportUtils();
}
/**
* 属性集合
*/
private final Map<Integer, Field> fieldMap = new HashMap<>();
/**
* 下标集合
*/
private final Map<Integer, ExcelImportField> indexMap = new HashMap<>();
/**
* 导入数据
* 默认 第一个sheet 标题栏在0 数据从1开始
*
* @param excelFile 数据文件
* @param beanClazz 转换的实体对象
* @param <T> 实体对象
* @return List<T>
*/
public <T> List<T> importData(MultipartFile excelFile, Class<T> beanClazz) {
return importData(excelFile, beanClazz, 0);
}
/**
* 导入数据
* 默认 第一个sheet 标题栏在0 数据从1开始
*
* @param excelFile 数据文件
* @param beanClazz 转换的实体对象
* @param sheetIndex sheet下标
* @param <T> 实体对象
* @return List<T>
*/
public <T> List<T> importData(MultipartFile excelFile, Class<T> beanClazz, int sheetIndex) {
return importData(excelFile, beanClazz, sheetIndex, 1);
}
/**
* 导入数据
*
* @param excelFile 数据文件
* @param beanClazz 转换的实体对象
* @param sheetIndex sheet下标
* @param rowStartIndex 数据开始下标
* @param <T> 实体对象
* @return List<T>
*/
public <T> List<T> importData(MultipartFile excelFile, Class<T> beanClazz, int sheetIndex, int rowStartIndex) {
if (ObjectUtil.isNull(excelFile)) {
log.error("【excelFile】excel文件为空");
return null;
}
if (ObjectUtil.isNull(beanClazz)) {
log.error("【beanClazz】beanClazz类为空");
return null;
}
Constructor<T> constructor = ReflectUtil.getConstructor(beanClazz);
if (ObjectUtil.isNull(constructor)) {
log.error("【beanClazz】{} 没有无参构造方式", beanClazz.getName());
return null;
}
this.parseImportField(beanClazz);
if (CollUtil.isEmpty(indexMap)) {
log.info("未找到需要解析的数据字段");
return null;
}
try {
byte[] bytes = excelFile.getBytes();
Workbook workbook = getWorkbook(new ByteArrayInputStream(bytes), excelFile.getContentType());
Sheet sheet = workbook.getSheetAt(sheetIndex);
// 获取所有行
return parseRow(beanClazz, sheet, rowStartIndex);
} catch (IOException e) {
log.error(e.getMessage());
}
return null;
}
/**
* 解析行数据
*
* @param sheet sheet对象
* @param rowStartIndex 数据开始索引
* @return List<Row>
*/
private <T> List<T> parseRow(Class<T> clazz, Sheet sheet, int rowStartIndex) {
// 最后一行数据的索引下标
int rowEnd = sheet.getPhysicalNumberOfRows();
List<T> list = new ArrayList<>(rowEnd - rowStartIndex + 1);
for (int rowNum = rowStartIndex; rowNum < rowEnd; rowNum++) {
Row row = sheet.getRow(rowNum);
// 反射构造对象,只支持无构造函数的对象
T t = ReflectUtil.newInstance(clazz);
list.add(t);
// 获取最后一列数据索引下标
short lastCellNum = row.getLastCellNum();
for (short i = 0; i < lastCellNum; i++) {
Cell cell = row.getCell(i);
if (ObjectUtil.isNotNull(cell)) {
String valStr = getCellValue(cell);
int index = Short.toUnsignedInt(i);
ExcelImportField importField = indexMap.get(index);
// 未找对应的数据
if (ObjectUtil.isNull(importField)) {
continue;
}
Field field = fieldMap.get(index);
Class<? extends ExcelImportFieldFormat<?>> format = importField.format();
// 格式转换
if (ObjectUtil.isNotNull(format)) {
ExcelImportFieldFormat<?> fieldFormat = FORMAT_MAP.get(format.getName());
if (ObjectUtil.isNull(fieldFormat)) {
// 未找到格式转换类,直接进行数据set
ReflectUtil.setFieldValue(t, field, valStr);
} else {
// 格式化数据
Object val = fieldFormat.format(valStr);
ReflectUtil.setFieldValue(t, field, val);
}
} else {
// 未找到格式转换类,直接进行数据set
ReflectUtil.setFieldValue(t, field, valStr);
}
}
}
}
return list;
}
/**
* 解析需要导入的字段
*
* @param beanClazz class
* @param <T> 返回类型
*/
private <T> void parseImportField(Class<T> beanClazz) {
Field[] fields = ClassUtil.getDeclaredFields(beanClazz);
for (Field field : fields) {
ExcelImportField annotation = AnnotationUtil.getAnnotation(field, ExcelImportField.class);
if (ObjectUtil.isNotNull(annotation)) {
int index = annotation.index();
if (index != -1) {
ExcelImportField importField = indexMap.get(index);
if (ObjectUtil.isNull(importField)) {
// 下标索引映射
indexMap.put(index, annotation);
} else {
log.error("下标索引重复,下标:{}", index);
}
// 字段对象映射
fieldMap.put(index, field);
Class<? extends ExcelImportFieldFormat<?>> format = annotation.format();
if (ObjectUtil.isNotNull(format)) {
try {
// 未找到需要转换的类,则进行添加数据
if (ObjectUtil.isNull(FORMAT_MAP.get(format.getName()))) {
FORMAT_MAP.put(format.getName(), format.newInstance());
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
} else {
log.error("下标索引错误,下标:{}", index);
}
}
}
}
/**
* 根据文件类型获取对应的工作簿对象
*
* @param inputStream 读取文件的输入流
* @param contentType 文件类型(xls或xlsx)
* @return 包含文件数据的工作簿对象
* @throws IOException IO异常
*/
private Workbook getWorkbook(InputStream inputStream, String contentType) throws IOException {
Workbook workbook = null;
if (XLS.equalsIgnoreCase(contentType)) {
workbook = new HSSFWorkbook(inputStream);
} else if (XLSX.equalsIgnoreCase(contentType)) {
workbook = new XSSFWorkbook(inputStream);
}
return workbook;
}
/**
* 获取默认数据
*
* @param cell 单元格cell
* @return 解析后的字符串
*/
private String getCellValue(Cell cell) {
if (ObjectUtil.isNull(cell)) {
return null;
}
switch (cell.getCellType()) {
// 数字类型
case 0:
double numericCellValue = cell.getNumericCellValue();
return NumberUtil.toStr(numericCellValue);
// 字符串类型
case 1:
return cell.getStringCellValue();
// 布尔类型
case 3:
boolean booleanCellValue = cell.getBooleanCellValue();
return BooleanUtil.toStringTrueFalse(booleanCellValue);
// 默认类型
default:
return StrUtil.EMPTY;
}
}
}
示例
- 需要转换的Bean
import lombok.Data;
/**
* @author xuyh0817
* @version 1.0.0
* @email xuyh0817@foxmail.com
* @date 2024/5/20 12:30
* @description 导入的bean
*/
@Data
public class Student {
/**
* 无参构造方法,必须
*/
public Student() {
}
/**
* 学号
*/
@ExcelImportField(index = 1, format = DefaultExcelImportFieldFormat.class)
private String no;
/**
* 姓名
*/
@ExcelImportField(index = 2, format = DefaultExcelImportFieldFormat.class)
private String name;
}
- 导入Excel示例
- 导入调用
public static void main(String[] args) {
// 默认sheet1,默认数据开始下标为1, 下标数据都从0开始
List<Student> studentList = ExcelImportUtils.getInstance().importData(excelFile, Student.class);
// 自定义sheet,sheet2 ,默认数据开始下标为1 , 下标数据都从0开始
List<Student> studentList1 = ExcelImportUtils.getInstance().importData(excelFile, Student.class, 1);
// 自定义sheet,sheet2 ,自定义数据开始行数 第3行开始, 下标数据都从0开始
List<Student> studentList2 = ExcelImportUtils.getInstance().importData(excelFile, Student.class, 2, 2);
}
总结
本本介绍了ExcelImportUtils工具类通过ExcelImportField注解进行Excel数据解析、数据填充到Bean中,简化了数据解析过程。通过ExcelImportFieldFormat接口,灵活转换数据格式。