读取excel,判断类型,获取到数据后转换成实体对象

package org.ecej.oms.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
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.ecej.scms.oms.entity.vo.scmCustomer.CustomerMasterDataOutputVO;

public class ReadExcel {

	public static void main(String[] args) throws Exception {
		String filePath = "D://960客户主数据(1).xlsx";
		List<List<Object>> readExcelList = readExcel(filePath);
		System.out.println(readExcelList);
		List<CustomerMasterDataOutputVO> outputVOList = new ArrayList<>();
		CustomerMasterDataOutputVO customerMasterDataOutputVO = new CustomerMasterDataOutputVO();
		for(List<Object> list : readExcelList) {
			listToModel(list, customerMasterDataOutputVO);
			System.out.println(customerMasterDataOutputVO.getCustNo() + "; "+ customerMasterDataOutputVO.getCompanyCode() + "; " + customerMasterDataOutputVO.getName() + "; ");
			outputVOList.add(customerMasterDataOutputVO);
		}
	}
	
	public static <T> void listToModel(List<Object> list, T t) throws Exception {
        Field[] fields = t.getClass().getDeclaredFields();
        if (list.size() != fields.length) {
            return;
        }
        for (int k = 0, len = fields.length; k < len; k++) {
            // 根据属性名称,找寻合适的set方法
            String fieldName = fields[k].getName();
            String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase()
                    + fieldName.substring(1);
            Method method = null;
            Class<?> clazz = t.getClass();
            try {
                method = clazz.getMethod(setMethodName, new Class[] { list.get(k).getClass() });
            } catch (SecurityException e1) {
                e1.printStackTrace();
                return;
            } catch (NoSuchMethodException e1) {
                String newMethodName = "set" + fieldName.substring(0, 1).toLowerCase()
                        + fieldName.substring(1);
                try {
                    method = clazz.getMethod(newMethodName, new Class[] { list.get(k).getClass() });
                } catch (SecurityException e) {
                    e.printStackTrace();
                    return;
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                    return;
                }
            }
            if (method == null) {
                return;
            }
            method.invoke(t, new Object[] { list.get(k) });
        }
    }


	/**
	 * 读取excel 第1张sheet (xls和xlsx)
	 * 
	 * @param filePath excel路径
	 * @param columns  列名(表头)
	 * @author lizixiang ,2018-05-08
	 * @return
	 */
	public static List<List<Object>> readExcel(String filePath) {
		String excelPath = filePath;
		List<List<Object>> list = null;
		try {
			File excel = new File(excelPath);
			if (excel.isFile() && excel.exists()) { // 判断文件是否存在

				String[] split = excel.getName().split("\\."); // .是特殊字符,需要转义!!!!!
				Workbook wb;
				// 根据文件后缀(xls/xlsx)进行判断
				if ("xls".equals(split[1])) {
					FileInputStream fis = new FileInputStream(excel); // 文件流对象
					wb = new HSSFWorkbook(fis);
				} else if ("xlsx".equals(split[1])) {
					wb = new XSSFWorkbook(excel);
				} else {
					System.out.println("文件类型错误!");
					return null;
				}

				// 开始解析
				Sheet sheet = wb.getSheetAt(0); // 读取sheet 0

				int firstRowIndex = sheet.getFirstRowNum() + 1; // 第一行是列名,所以不读
				int lastRowIndex = sheet.getLastRowNum(); //总行数
//				System.out.println("firstRowIndex: " + firstRowIndex);
//				System.out.println("lastRowIndex: " + lastRowIndex);
				list = new ArrayList<>();
				for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { // 遍历行
//					System.out.println("rIndex: " + rIndex);
					List<Object> tempList = new ArrayList<>();
					Row row = sheet.getRow(rIndex);
					if (row != null) {
						int firstCellIndex = row.getFirstCellNum();
						int lastCellIndex = row.getLastCellNum();
						for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { // 遍历列
							Cell cell = row.getCell(cIndex);
							if (cell != null) {
//								System.out.print(cell.toString());
							}
							tempList.add(cell.toString());
						}
					}
					list.add(tempList);
				}
				
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值