java excel导入

传入一个文件

public List<User > impUser(MultipartFile file) {
        //总行数
          int totalRows = 0;
        //总条数
          int totalCells = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<User > dataLi = new LinkedList<>();
        try {
            Workbook wb = null;
        String fileName = file.getOriginalFilename();//获取文件名
        if (fileName.matches("^.+\\.(?i)(xls)$")) {
            // Excel 2003
            wb = new HSSFWorkbook(file.getInputStream());
        } else if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            // Excel 2007/2010
            wb = new XSSFWorkbook(file.getInputStream());
        }
            // 得到第一个shell
            Sheet sheet = wb.getSheetAt(0);
            // 得到Excel的行数
            totalRows = sheet.getPhysicalNumberOfRows();
            // 得到Excel的列数(前提是有行数)
            if (totalRows > 1 && sheet.getRow(0) != null) {
                totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }
            // 循环Excel行数
            for (int r = 1; r < totalRows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                User user= new User ();
                // 循环Excel的列
                for (int c = 0; c < totalCells; c++) {
                    Cell cell = row.getCell(c);
                    if (null != cell) {
                        if (c == 0) {           //第一列
                        user.setName(cell.getStringCellValue);
                        }
                        else if (c == 1){
                            user.setAge(new BigDecimal(cell.getNumericCellValue()));
                         
                        }
                        else if (c == 2){
                            user.setSex(new BigDecimal(cell.getNumericCellValue()));
                      
                        }
                     
                    }
                }
                dataLi.add(energyConsumption);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataLi;
    }

拿到数据通过MyBatis遍历插入到数据库中

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值