目录
在java后端开发中经常遇到开发Excel数据批量导入的需求,那么在导入的过程中,需要读取Excel数据,并将数据转换成实体对象,才能进行保存到数据库。如果是逐个字段读取转换,十分低效、麻烦且不优雅。下面带来一个基于注解实现的支持中文表头的读取Excel数据并转换为实体对象列表的工具类,使用该工具类可将Excel数据转换成任意实体任意字段。关注微行公众号:“GIS工具乐园”,持续更新开发技巧分享哦。
工具类源代码下载:https://download.csdn.net/download/tylkhx/85196823
一、实现效果
现在以导入学生信息为例,新建了一个java实体和相对应的Excel表格,数据如下:
1.转换效果
2.Excel表格数据
3.学生实体
public class StudentDTO {
@ExcelImportField(name = "姓名")
private String name;
@ExcelImportField(name = "性别")
private String sex;
@ExcelImportField(name = "年龄")
private String age;
@ExcelImportField(name = "电话")
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
二、实现代码
1.代码思路
本工具类基于的hutool包的api编写,但是直接hutool读取Excel的话,需要实体对象的字段名与Excel表头完全一致,因此直接使用hutool的话不支持中文表头,这对用户使用带来不便,本工具类基于注解实现表头的转换,支持中文在内的任意表头,同时使用泛型实现通用的Excel数据实体对象列表转换。
2.Excel导入字段注解代码
在此注解中的name值指定Excel表头内
/**
* EXCEL导入字段注解
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelImportField {
String name(); //excel中表头名字
}
3.读取Excel数据核心方法
public static <T>List<T> read(ExcelReader reader,int sheetIndex,int headerRowIndex, int startRowIndex, Class<T> modelClass){
Field[] fields = modelClass.getDeclaredFields();
if (fields == null || fields.length == 0){
return new ArrayList<>();
}
Map<String,String> fieldMap = new HashMap<>();
Field field = fields[i];
if (!field.isAnnotationPresent(ExcelImportField.class)) {
continue;
}
ExcelImportField excelImportField = field.getAnnotation(ExcelImportField.class);
String aliasName = excelImportField.name();
String fieldName = field.getName();
fieldMap.put(aliasName,fieldName);
}
Sheet sheet = reader.getWorkbook().getSheetAt(sheetIndex);
Row row = sheet.getRow(headerRowIndex);
Iterator<Cell> cellIterator = row.iterator();
while (cellIterator.hasNext()){
Cell cell = cellIterator.next();
String old = cell.getStringCellValue();
cell.setCellValue(fieldMap.get(old));
}
return reader.read(headerRowIndex, startRowIndex, modelClass);
}
4.调用示例
public static void main(String[] args) {
String path = "E:\\开发项目\\demo\\doc\\excel导入示例\\学生信息.xlsx";
File file = new File(path);
List<StudentDTO> read = read(file, 0, 0, 1, StudentDTO.class);
int i=1;
}
三、使用方法
首先在实体对象字段中添加ExcelImportField注解,并在注解的name值指定Excel表头内容,然后使用工具类读取Excel数据即可