通过反射进行excel导入数据,无论实体类属性多少都可使用

本文介绍如何通过反射技术实现Excel数据导入到Java实体类,适用于任意数量的实体属性,详细步骤包括接收Excel文件、创建Excel数据的实体类列表、转换方法以及Excel操作Util模板的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文章都是自创,如有类同纯属巧合,转发的朋友请写我的文章链接

excel的导入

1.接收方法

	@RequestMapping("imp")
    @ResponseBody
    public Result imp(MultipartFile file) throws IOException, InvalidFormatException, ParseException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {	//接受file
        /*HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());*/
        Workbook workbook = WorkbookFactory.create(file.getInputStream());//创建workbook
        Sheet sheet = workbook.getSheetAt(0);	//创建sheet
       	List<User> users = importData(sheet);  //将导入的具体操作独立成一个方法
		UserService.imp(users);//调用方法向数据库存储
        return result();
}

2. 写一个excel对应实体属性的list

//list为头一个字母大写的属性名
private ArrayList<String> list = new ArrayList<String>(Arrays.asList(
            "Name","Sex","ShenGao","TiZhong","Dept"
    ));

3.写将excel信息转换成实体类的方法

//导入的具体方法
private List<User> importData(Sheet sheet) throws ParseException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        List<User> user= new ArrayList<>();
        int lastRowNum = sheet.getLastRowNum(); //excel的条数
        for (int i = 0; i < lastRowNum; i++) {
            User user= new User();	 //导入的实体类
            Field[] fields = user.getClass().getDeclaredFields(); //通过反射获取field数组
            Map<String, Integer> map = new HashMap<>();
            Row row = sheet.getRow(i + 1);	//将第一行标题行跳过否则会报错
            //通过反射获取field数组
            for (int i1 = 0; i1 < fields.length; i1++) {
                Field declaredField = fields[i1];
                // 获取属性的名字
                String name = declaredField.getName();
                // 将属性的首字符大写,方便构造get,set方法
                name = name.substring(0, 1).toUpperCase() + name.substring(1);
                map.put(name, i1);
            }
            //list为excel对应的字段
            for (int j = 0; j < list.size(); j++) {
                String s = list.get(j);
                Cell cell = row.getCell(j);
                Integer integer = map.get(s);
                if (integer != null) { //判断是否有这个属性
                    Field field = fields[integer];
                    setPattern(field,cell,user,s);//将cell中的内容放到对应属性中
                }
            }
            users.add(user);
        }

        return users;
    }

setPattern对应的方法及作用

private void setPattern(Field field,Cell cell,User user,String s) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ParseException {
		//判断cell中是否有数据
        if (cell == null) {
            return;
        }
        //反射中有获取属性数据类型的方法
        String type = field.getGenericType().toString();
		
		//判断属性类型
        if (type.equals("class java.lang.String")) {
            Method m = user.getClass().getMethod("set" + s,String.class);//反射执行set时一定要写属性的数据类型
            m.invoke(user, ExcelUtil.cellStringValue(cell));//使用util中对应类型的方法转换cell中的内容
        }
        if (type.equals("class java.lang.Integer")) {
            Method m = user.getClass().getMethod("set" + s,Integer.class);
            m.invoke(user, ExcelUtil.cellIntegerValue(cell));
        }
        if (type.equals("class java.lang.Short")) {
            Method m = user.getClass().getMethod("set" + s,Short.class);
            m.invoke(user, ExcelUtil.cellShortValue(cell));
        }
        if (type.equals("class java.lang.Double")) {
            Method m = user.getClass().getMethod("set" + s,Double.class);
            m.invoke(user, ExcelUtil.cellDoubleValue(cell));
        }
        if (type.equals("class java.lang.Boolean")) {
            Method m = user.getClass().getMethod("set" + s,Boolean.class);
            m.invoke(user, ExcelUtil.cellBooleanValue(cell));
        }
        if (type.equals("class java.util.Date")) {
            Method m = user.getClass().getMethod("set" + s,Date.class);
            m.invoke(user, ExcelUtil.cellDateVlaue(cell));
        }

    }

excel的对应操作util模板

package com.aisino.zhgl.zichan.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExcelUtil {
    /**
     * 获取number(*,*)类型数据
     * @param cell
     * @return
     */
    public static Double cellDoubleValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        return cell.getNumericCellValue();//这是OPI提供的方法,获取数字格式的方法
    }
    /**
     * 获取number类型数据
     * @param cell
     * @return
     */
    public static Integer cellIntegerValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        Double d = cell.getNumericCellValue();
        return d.intValue();//进行数据转换主要是怕set属性的时候报数据转换异常
    }

    public static Short cellShortValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        Double d = cell.getNumericCellValue();
        Short aShort = (short) d.intValue();
        return aShort;
    }

    public static boolean cellBooleanValue(Cell cell) {
        boolean b = cell.getBooleanCellValue();
        return b;
    }

    /**
     * 获取date类型的数据
     * @param cell
     * @return
     * @throws ParseException
     */
    public static Date cellDateVlaue(Cell cell) throws ParseException {
        if (cell == null) {
            return null;
        }
        //date类型是属于cell_type_numeric类型的
        if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
            //使用poi提供的方法判断是否是date类型必须是在cell是CELL_TYPE_NUMERIC情况下判断如果是其他类型的直接判断会报异常
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                Date d = cell.getDateCellValue(); //OPI提供的获取date类型的数据,有时在excel中会将数据直接转换成excel中date类型
                return d;
            }
        }
        //如果表格没有自动转换成date类型,使用DateFormat转换成date
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String s = cell.getStringCellValue().trim();
        Date date = format.parse(s);

        return date;
    }

    /**
     * 对应string类型
     * @param cell
     * @return
     */
    public static String cellStringValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
            //如果cell是date转换成string
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                Date dateCellValue = cell.getDateCellValue();
                String format1 = format.format(dateCellValue);
                return format1;
            }
            //下面对应年份之类的,只是2020对应cell是CELL_TYPE_NUMERIC不是date,将对应的数字转换成String
            Double numbe = cell.getNumericCellValue();
            String s = Integer.toString(numbe.intValue());
            return s;
        }
        //如果是string就可以直接返回。
        return cell.getStringCellValue().trim();
    }
}

serviceImpl中的方法

@Override
    public void imp(List<User> users) {
        for (User user: users) {
            dao.insert(user);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值