Java工具集-Excel行转换为对象工具类

2020-06-10 15:48:57 浏览数 (1)

代码示例
代码语言:javascript复制
package com.simple.util.poi;

import com.simple.util.time.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: simple_tools
 * @description: Excel行转换为对象工具类
 * @author: Mr.chen
 * @create: 2020-06-09 09:50
 **/
public class ExcelRowConvert2ObjectUtil {
    /**
     * 检查表头
     *
     * @param headRow
     */
    private Map<String, Integer> checkTableHead(Map<String, String> headMap, List<String> headRow) {
        if (CollectionUtils.isEmpty(headRow)) {
            throw new RuntimeException("import data is empty");
        }
        Map<String, Integer> indexMap = new HashMap<String, Integer>();
        int repeat = 0;
        int index = 0;
        boolean flag = false;
        for (String columnName : headRow) {
            repeat = 0;
            for (Map.Entry<String, String> mp : headMap.entrySet()) {
                if (mp.getKey().equals(StringUtils.trim(columnName))) {
                      repeat;
                    flag = true;
                }
            }
            if (repeat > 1) {
                throw new RuntimeException("import data is empty");
            }
            if (!flag) {
                throw new RuntimeException("import data is empty");
            }
            indexMap.put(columnName, index);
              index;
        }
        return indexMap;
    }

    /**
     * 处理数据
     * @param cls
     * @param headMap
     * @param sheets
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> toList(Class<?> cls, Map<String, String> headMap, List<DataGird> sheets) {
        if (cls == null) {
            throw new RuntimeException("object is not exsit");
        }
        if (headMap == null || headMap.size() <= 0) {
            throw new RuntimeException("import data is empty");
        }
        // 第一个样单
        DataGird excel = sheets.get(0);
        List<List<String>> rows = excel.getData();
        if (CollectionUtils.isEmpty(rows) && rows.size() <= 1) {
            throw new RuntimeException("操作失败 导入数据为空");
        }
        // 标题行
        List<String> headRow = rows.get(0);
        Map<String, Integer> map = this.checkTableHead(headMap, headRow);
        List<T> objs = new ArrayList<T>();
        T instance = null;
        try {
            Field[] fields = cls.getDeclaredFields();
            List<String> datas = null;
            for (int i = 1, length = rows.size(); i < length; i  ) {
                datas = rows.get(i);
                instance = (T) cls.newInstance();
                for (String headName : headRow) {
                    for (Map.Entry<String, Integer> mp : map.entrySet()) {
                        if (mp.getKey().equals(headName)) {
                            String column = headMap.get(headName);
                            int index = mp.getValue().intValue();
                            if (datas.size() > index) {
                                String value = datas.get(index);
                                for (Field field : fields) {
                                    if (field.getName().equals(column)) {
                                        field.setAccessible(true);
                                        String fldtype = field.getType().getSimpleName();
                                        if ("String".equals(fldtype)) {
                                            field.set(instance, value);
                                        } else if ("Double".equals(fldtype)) {
                                            double val = Double.valueOf(StringUtils.isNotBlank(value) ? Double.parseDouble(value) : 0);
                                            field.set(instance, val);
                                        } else if ("Float".equals(fldtype)) {
                                            float val = Float.valueOf(StringUtils.isNotBlank(value) ? Float.parseFloat(value) : 0);
                                            field.set(instance, val);
                                        } else if ("Integer".equals(fldtype)) {
                                            int val = Integer.valueOf(StringUtils.isNotBlank(value) ? Integer.parseInt(value) : 0);
                                            field.set(instance, val);
                                        } else if ("Date".equals(fldtype)) {
                                            Date val = DateUtil.parseDate(value, new String[]{"yyyy-MM-dd"});
                                            field.set(instance, val);
                                        } else if ("Long".equals(fldtype)) {
                                            long val = Long.valueOf(StringUtils.isNotBlank(value) ? Long.parseLong(value) : 0);
                                            field.set(instance, val);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
                objs.add(instance);
            }
        } catch (Exception e) {
            throw new RuntimeException("操作失败");
        }

        return objs;
    }
}

class DataGird implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String title; // 标题
    private List<List<String>> data; // 数据
    private int columns; // 列数

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<List<String>> getData() {
        return data;
    }

    public void setData(List<List<String>> data) {
        this.data = data;
    }

    public int getColumns() {
        return columns;
    }

    public void setColumns(int columns) {
        this.columns = columns;
    }

}

0 人点赞