All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.houbb.iexcel.hutool.support.sax.DefaultSaxReadConvert Maven / Gradle / Ivy

There is a newer version: 1.6.0
Show newest version
package com.github.houbb.iexcel.hutool.support.sax;

import com.github.houbb.heaven.util.lang.StringUtil;
import com.github.houbb.heaven.util.lang.reflect.ClassUtil;
import com.github.houbb.heaven.util.lang.reflect.ReflectFieldUtil;
import com.github.houbb.iexcel.hutool.annotation.ExcelField;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class DefaultSaxReadConvert implements SaxReadConvert {

    /**
     * 头信息
     */
    private List headerNameList = new ArrayList<>();

    @Override
    public T convert(Class tClass, int rowIndex, List rowList) {
        if(rowIndex == 0) {
            headerNameList = rowList.stream().map(StringUtil::objectToString).collect(Collectors.toList());
            return null;
        } else {
            // 转换处理
            List fields = ClassUtil.getAllFieldList(tClass);
            T instance = ClassUtil.newInstance(tClass);

            for(int i = 0; i < fields.size(); i++) {
                Field field = fields.get(i);
                Object value = getFieldReadValue(field, i, rowList);

                // 设置
                ReflectFieldUtil.setValue(field, instance, value);
            }

            return instance;
        }
    }

    private Object getFieldReadValue(Field field, int index, List rowList) {
        ExcelField excelField = field.getAnnotation(ExcelField.class);
        if(excelField == null) {
            return null;
        }
        if(!excelField.readRequire()) {
            return null;
        }

        String headerName = excelField.headerName();
        int headerIndex = getHeaderIndex(index, headerName);

        return StringUtil.objectToString(rowList.get(headerIndex));
    }


    private int getHeaderIndex(int fieldIndex,
                         String headerName) {
        int headerNameIndex = headerNameList.indexOf(headerName);
        if(headerNameIndex >= 0) {
            return headerNameIndex;
        }

        return fieldIndex;
    }

}