java poi通过反射进行批量导入工具类

 

/**
     * 
     * excel数据 读取
     *
     * @author 
     * @version [VCES V201R001, 2017年12月11日]
     *
     * @param customClass  实体类
     * @param workbook  excel 
     * @param indexSheet    sheet 下标
     * @param startingLine   数据起始行
     * @param attr  实体类对应字段名称数组,
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InstantiationException
     */
    public static <T> List<T> excelImportBoty(Class<T> customClass, HSSFWorkbook workbook,
            Integer indexSheet, Integer startingLine, String[] attr) throws Exception {
        List<T> result = new ArrayList<T>();
        // 获取sheet
        HSSFSheet sheetAt = workbook.getSheetAt(indexSheet);
        // 获取总行数
        int lastRowNum = sheetAt.getLastRowNum();
        HSSFRow createRow = null;
        Field commandField;
        // 开始循环读取数据 ,从数据其实行开始
        for (int i = startingLine; i < lastRowNum + 1; i++) {
            createRow = sheetAt.getRow(i);
            T ob = customClass.newInstance();// 创建实例化对象,创建新的存储数据的对象
            // 遍历所有属性值
            for (int j = 0; j < attr.length; j++) {
                commandField = customClass.getDeclaredField(attr[j]);
                // 开启属性访问权限
                commandField.setAccessible(true);
                // 获取数据
                String data = createRow.getCell(j).toString();
                // 判断属性的类型
                if (commandField.getType().toString().equals("class java.lang.String")) {
                    // 将读入的数据(在con中)封装到对象(ob)的属性(fi[i])中
                    commandField.set(ob, data);
                } else if (commandField.getType().toString().equals("class java.math.BigDecimal")) {
                    commandField.set(ob, new BigDecimal(data));//
                } else if (commandField.getType().toString().equals("class java.math.BigInteger")) {
                    commandField.set(ob, new BigInteger(data));// 将信息封装到对象中
                } else if (commandField.getType().toString().equals("class java.lang.Integer")) {
                    commandField.set(ob, Integer.valueOf(data));// 将信息封装到对象中
                }

            }
            result.add(ob);
        }
        return result;

    }


 

转载于:https://www.cnblogs.com/cjbbk/p/8057300.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值