基于poi,将excel表转化为实体类列表的工具类

基于poi,将excel表转化为实体类列表的工具类

写作很幸苦转载请注明!!!!!

package com.fxx.bos.utils;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;


public class GetBeanListByExcel {
	/**
	 * 
	 * @param filePath excel文件路径
	 * @param cellKey excel文件每列对应实体类属性名称数组 如String[] cellKey = {"id","province","city","district","postcode"};
	 * @param c 实体类Class
	 * @return 根据excel表每行的记录生成的实体类list
	 * @throws Exception
	 */
	public static <T>List<T> getBeanList(String filePath,String[] cellKey,Class<T> c) throws Exception{
		//创建实体类对象容器
		List<T> beanList = new ArrayList<T>();
		//读取excel文件
		POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(filePath));   
		@SuppressWarnings("resource")
		HSSFWorkbook xlsFile = new HSSFWorkbook(fs);
		HSSFSheet sheet = xlsFile.getSheetAt(0); 
		//判断属性列表同excel文件列是否相符,避免数组范围溢出
		if(cellKey.length!=sheet.getRow(0).getLastCellNum()) {
			throw new RuntimeException("传入列名参数不符合条件!");
		}
		//创建属性map
		HashMap<String, String> valueMap = new HashMap<String, String>();
		//遍历excel文件
		for (Row row : sheet) {
			for(int i=0;i<cellKey.length;i++) {
				valueMap.put(cellKey[i], row.getCell(i).getStringCellValue());
			}
			T t = c.newInstance();
			//使用BeanUtils将封装的属性注入对象
			BeanUtils.populate(t, valueMap);
			//将对象添加至容器
			beanList.add(t);
		}
		return beanList;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值