com.github.kunalk16.excel.objectmapper.ExcelObjectFromWorkbookMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lightExcelReader Show documentation
Show all versions of lightExcelReader Show documentation
A lightweight Java framework to read .xlsx excel files.
The newest version!
package com.github.kunalk16.excel.objectmapper;
import com.github.kunalk16.excel.model.user.Sheet;
import com.github.kunalk16.excel.model.user.WorkBook;
import com.github.kunalk16.excel.objectmapper.annotations.ExcelSheet;
import com.github.kunalk16.excel.objectmapper.extractor.FieldsFromClassExtractor;
import com.github.kunalk16.excel.objectmapper.filter.ValidWorkBookFilter;
import com.github.kunalk16.excel.utils.logger.ExcelReaderLogger;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Objects;
public class ExcelObjectFromWorkbookMapper {
static T createObjectFromWorkBook(WorkBook workBook, Class modelClass) {
if (Objects.nonNull(modelClass) && new ValidWorkBookFilter().test(workBook)) {
Map fieldsFromClass = new FieldsFromClassExtractor<>(ExcelSheet.class).apply(modelClass);
if (fieldsFromClass.isEmpty()) {
return null;
}
T instance = createInstance(modelClass);
if (Objects.isNull(instance)) {
return null;
}
for (String name : fieldsFromClass.keySet()) {
Sheet sheet = workBook.getSheet(name);
Field field = fieldsFromClass.get(name);
addListToField(instance, sheet, field);
}
return instance;
}
return null;
}
private static T createInstance(Class modelClass) {
try {
return modelClass.newInstance();
} catch (Exception e) {
ExcelReaderLogger.getInstance().severe("Could not create model instance " + e.getLocalizedMessage());
return null;
}
}
private static void addListToField(T instance, Sheet sheet, Field field) {
try {
if (Objects.nonNull(sheet)) {
ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
Type genericParameterType = parameterizedType.getActualTypeArguments()[0];
Class> classOfSheet = Class.forName(genericParameterType.getTypeName());
field.setAccessible(true);
field.set(instance, ExcelObjectFromSheetMapper.createObjectFromSheet(classOfSheet, sheet.getRows().iterator()));
}
} catch (Exception e) {
ExcelReaderLogger.getInstance().warning(e.getLocalizedMessage());
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy