解析Excel

package com.jpcar.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jpcar.model.entity.ToolboxValue;

public class ExcelUtil {
    private static final char UNDERLINE = '_';

    public static void main(String[] args) throws Exception {
    Map<String, String> map = new HashMap<>();
    map.put("toolboxId", "toolbox_id");
    InputStream in = new FileInputStream(new File("F:\\test\\config\\toolbox_value.xlsx"));
    List<ToolboxValue> list = parse(in, ToolboxValue.class, map);
    System.out.println(list);
    System.out.println("-------------------------");
    System.out.println(toJsonByExcel(list, ToolboxValue.class, map));
    }

    public static <T> List<T> parse(InputStream in, Class<T> cla) throws Exception {
    return parse(in, cla, null);
    }

    /**
     * 
     * @param in
     * @param cla
     * @param mapper
     *            Map<FieldName, ExcelName>
     * @return
     * @throws IOException
     */
    public static <T> List<T> parse(InputStream in, Class<T> cla, Map<String, String> mapper) throws Exception {
    List<T> list = new ArrayList<>();
    Field[] fs = cla.getDeclaredFields();
    Map<String, Field> map = new HashMap<>();
    for (Field f : fs) {
        String fn = f.getName();
        if (null != mapper) {
        fn = mapper.get(fn);
        if (null == fn)
            fn = camelToUnderline(f.getName());
        } else {
        fn = camelToUnderline(fn);
        }
        map.put(fn, f);
    }

    XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
    XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);

    int rowstart = xssfSheet.getFirstRowNum();
    int rowEnd = xssfSheet.getLastRowNum();
    int cellSize = xssfSheet.getRow(0).getPhysicalNumberOfCells();
    List<String> keys = new ArrayList<>();
    for (int i = rowstart; i <= rowEnd; i++) {
        if (i == 0) {
        XSSFRow row = xssfSheet.getRow(0);
        for (int j = 0; j < cellSize; j++) {
            String key = row.getCell(j).getStringCellValue();
            keys.add(key);
        }
        continue;
        }
        T t = cla.newInstance();
        XSSFRow row = xssfSheet.getRow(i);
        for (int j = 0; j < cellSize; j++) {
        String str = keys.get(j);
        Field f = map.get(str);
        if (null == f)
            continue;
        f.setAccessible(true);
        String type = f.getType().getName();
        XSSFCell cell = row.getCell(j);
        if (type.equals("int") || "java.lang.Integer".equals(type)) {
            int val = (int) cell.getNumericCellValue();
            f.set(t, val);
        } else if ("double".equals(type) || "java.lang.Double".equals(type)) {
            double val = cell.getNumericCellValue();
            f.set(t, val);
        } else if ("java.lang.String".equals(type)) {
            String val = "";
            if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
            val = (int) cell.getNumericCellValue() + "";
            } else {
            val = cell.getStringCellValue();
            }
            f.set(t, val);
        } else if ("boolean".equals(type) || "java.lang.Boolean".equals(type)) {
            boolean val = cell.getBooleanCellValue();
            f.set(t, val);
        } else if ("java.util.Date".equals(type)) {
            Date val = cell.getDateCellValue();
            f.set(t, val);
        }
        }
        list.add(t);
    }

    return list;
    }

    public static <T> String toJsonByExcel(List<T> list, Class<T> cla) throws Exception {
    return toJsonByExcel(list, cla, null);
    }

    public static <T> String toJsonByExcel(List<T> list, Class<T> cla, Map<String, String> mapper) throws Exception {
    if (null == list || list.size() == 0)
        return null;
    Field[] fs = cla.getDeclaredFields();
    List<Map<String, Object>> l = new ArrayList<>();
    for (T t : list) {
        Map<String, Object> map = new HashMap<>();
        for (Field f : fs) {
        f.setAccessible(true);
        Object obj = f.get(t);
        if (null == obj) {
            String type = f.getType().getName();
            if (type.equals("int") || "java.lang.Integer".equals(type)) {
            obj = 0;
            } else if ("double".equals(type) || "java.lang.Double".equals(type)) {
            obj = 0.0;
            } else if ("boolean".equals(type) || "java.lang.Boolean".equals(type)) {
            obj = false;
            } else {
            obj = "";
            }
        }
        String key = f.getName();
        if (key.equals("serialVersionUID"))
            continue;
        if (null != mapper) {
            key = mapper.get(key);
            if (null == key)
            key = camelToUnderline(f.getName());
        } else {
            key = camelToUnderline(key);
        }
        map.put(key, obj);
        }
        l.add(map);
    }
    return JSON.toJSONString(l, SerializerFeature.WriteNullNumberAsZero,
        SerializerFeature.WriteNonStringValueAsString);
    }

    public static String underlineToCamel(String str) {
    if (str == null || "".equals(str.trim())) {
        return "";
    }
    int len = str.length();
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++) {
        char c = str.charAt(i);
        if (c == UNDERLINE) {
        if (++i < len) {
            sb.append(Character.toUpperCase(str.charAt(i)));
        }
        } else {
        sb.append(c);
        }
    }
    return sb.toString();
    }

    public static String camelToUnderline(String param) {
    if (param == null || "".equals(param.trim())) {
        return "";
    }
    int len = param.length();
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++) {
        char c = param.charAt(i);
        if (Character.isUpperCase(c)) {
        sb.append(UNDERLINE);
        sb.append(Character.toLowerCase(c));
        } else {
        sb.append(c);
        }
    }
    return sb.toString();
    }
}

 

posted @ 2017-06-30 11:49  不知为何就叫呵呵  阅读(248)  评论(0编辑  收藏  举报