com.github.bingoohuang.excel2beans.RowObjectCreator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of excel2javabeans Show documentation
Show all versions of excel2javabeans Show documentation
a little utility to convert excel rows to java beans
package com.github.bingoohuang.excel2beans;
import com.github.bingoohuang.instantiator.BeanInstantiator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
class RowObjectCreator {
private final List beanFields;
private final boolean cellDataMapAttachable;
private final Sheet sheet;
private final Row row;
private final Table imageDataTable;
private final DataFormatter cellFormatter;
private final Map cellDataMap;
private final T object;
private int emptyNum;
@SuppressWarnings("unchecked")
public RowObjectCreator(BeanInstantiator instantiator,
List beanFields,
boolean cellDataMapAttachable,
Sheet sheet,
Table imageDataTable,
DataFormatter cellFormatter,
int rowNum) {
this.beanFields = beanFields;
this.cellDataMapAttachable = cellDataMapAttachable;
this.cellDataMap = cellDataMapAttachable ? Maps.newHashMap() : null;
this.sheet = sheet;
this.imageDataTable = imageDataTable;
this.cellFormatter = cellFormatter;
this.row = sheet.getRow(rowNum);
this.object = this.row == null ? null : instantiator.newInstance();
}
public T createObject() {
if (object == null) return null;
processRow();
if (emptyNum == beanFields.size()) return null;
if (cellDataMapAttachable)
((CellDataMapAttachable) object).attachCellDataMap(cellDataMap);
return object;
}
private void processRow() {
for (val beanField : beanFields) {
val fieldValue = new BeanFieldValueCreator(beanField).parseFieldValue();
if (fieldValue == null) {
++emptyNum;
} else {
beanField.setFieldValue(object, fieldValue);
}
}
}
@RequiredArgsConstructor
private class BeanFieldValueCreator {
private final ExcelBeanField beanField;
public Object parseFieldValue() {
return beanField.isMultipleColumns() ? parseMultipleFieldValue()
: processSingleColumn(beanField.getColumnIndex(), -1);
}
private Object parseMultipleFieldValue() {
int nonEmptyFieldValues = 0;
List