@Excel注解将字段转换并且忽略大小写
时间: 2024-05-01 22:22:55 浏览: 120
在Java中,使用注解可以很方便地实现字段转换和忽略大小写的功能。具体实现如下:
1. 定义注解类ExcelField,用于标记需要转换的字段。
```
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
String value() default "";
}
```
2. 在需要转换的字段上添加ExcelField注解,并指定转换后的字段名。
```
public class User {
@ExcelField("用户名")
private String username;
@ExcelField("邮箱")
private String email;
//...
}
```
3. 定义一个工具类ExcelUtil,用于读取Excel文件并转换成对象列表。
```
public class ExcelUtil {
public static <T> List<T> readExcel(String filePath, Class<T> clazz) throws Exception {
List<T> list = new ArrayList<>();
Workbook workbook = WorkbookFactory.create(new File(filePath));
Sheet sheet = workbook.getSheetAt(0);
List<String> headers = getHeader(sheet.getRow(0));
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
T obj = clazz.newInstance();
for (int j = 0; j < headers.size(); j++) {
String header = headers.get(j);
Cell cell = row.getCell(j);
Field field = getField(clazz, header);
if (field != null && cell != null) {
field.setAccessible(true);
field.set(obj, convertValue(field.getType(), cell.getStringCellValue()));
}
}
list.add(obj);
}
return list;
}
private static List<String> getHeader(Row row) {
List<String> headers = new ArrayList<>();
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if (cell != null) {
headers.add(cell.getStringCellValue());
}
}
return headers;
}
private static Field getField(Class<?> clazz, String header) {
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(ExcelField.class)) {
ExcelField excelField = field.getAnnotation(ExcelField.class);
if (excelField.value().equalsIgnoreCase(header)) {
return field;
}
} else if (field.getName().equalsIgnoreCase(header)) {
return field;
}
}
return null;
}
private static Object convertValue(Class<?> clazz, String value) {
if (clazz == String.class) {
return value;
} else if (clazz == int.class || clazz == Integer.class) {
return Integer.parseInt(value);
} else if (clazz == double.class || clazz == Double.class) {
return Double.parseDouble(value);
} else {
return value;
}
}
}
```
4. 使用ExcelUtil读取Excel文件并转换成对象列表。
```
public static void main(String[] args) throws Exception {
List<User> users = ExcelUtil.readExcel("user.xlsx", User.class);
for (User user : users) {
System.out.println(user.getUsername() + "," + user.getEmail());
}
}
```
这样就可以实现对Excel文件中的字段进行转换,并且忽略大小写了。
阅读全文