导入文件xlsx

1 篇文章 0 订阅

一样,直接上代码
首先Controller,使用MultipartFile接受文件

	@PostMapping(value = "/importFile")
    @ApiOperation("导入学生模板")
    @TokenInfo
    public Result<String> importFile(MultipartFile file, @ApiIgnore LoginUser loginUser) {
        return excelService.importFile(file,loginUser);
    }
    

service

Result<String> importFile(MultipartFile file, LoginUser loginUser);

Impl

/**
     * 导入学生信息表
     * @param file
     * @param loginUser
     * @return
     */
    @Override
    public Result<String> importFile(MultipartFile file, LoginUser loginUser) {
        Result<String> result = new Result<>();
        if (file.getSize() == 0) {
            //"导入信息失败! 文件数据为空"
            return result.error500("导入信息失败! 文件数据为空");
        }
        StringBuilder failureMsg = new StringBuilder();
        CommonsMultipartFile cFile = (CommonsMultipartFile) file;
        DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
        Workbook workbook;
        try {
            workbook = WorkbookFactory.create(fileItem.getInputStream());
            //获取第一张Sheet表
            Sheet sheet = workbook.getSheetAt(0);
            //Sheet的行是从0开始
            int endRow = sheet.getLastRowNum() + 1; //获取需要读取内容的结束行标
            List<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
            if (endRow > 1) {
                for (int i = 1; i < endRow; i++) {//这里从第1开始下标是因为我Excel文件标题有1行
                    ArrayList<String> array = new ArrayList<String>();
                    Row row = sheet.getRow(i);
                    for (Cell cell : row) {
                        String value = null;
                        //判断时间格式
                        if (!cell.toString().equals("") && ("yyyy/mm;@".equals(cell.getCellStyle().getDataFormatString()) || "m/d/yy".equals(cell.getCellStyle().getDataFormatString())
                                || "yy/m/d".equals(cell.getCellStyle().getDataFormatString()) || "mm/dd/yy".equals(cell.getCellStyle().getDataFormatString())
                                || "dd-mmm-yy".equals(cell.getCellStyle().getDataFormatString()) || "yyyy/m/d".equals(cell.getCellStyle().getDataFormatString())))
                        {
                            // 获取日期类型的单元格的值
                            Date d = cell.getDateCellValue();
                            // 进行格式转换
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                            value = formatter.format(d);
                        }else{
                            cell.setCellType(Cell.CELL_TYPE_STRING);//根据不同类型转化成字符串
                            value = cell.getStringCellValue();//如果上面转化不行就直接 ""+cell.getStringCellValue();
                        }
                        array.add(value);
                    }
                    lists.add(array);
                }
            }
            //转化为对象
            List<BizStudentBatchAddInDto> list = this.setStuDto(lists);

            return result.success("导入成功!");
        } catch (InvalidFormatException e) {
            log.error("导入失败",e);
        } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
            log.error("导入失败",e);
        } catch (IOException e) {
            log.error("导入失败",e);
        }
        return result.success("");
    }

转化成对象

public List<BizStudentBatchAddInDto> setStuDto(List<ArrayList<String>> lists){
        List<BizStudentBatchAddInDto> list=new ArrayList<>();
        //拿出里面的所有值
        lists.forEach(item->{
            //遍历一次为一个对象
            BizStudentBatchAddInDto bizStudentBatchAddInDto=new BizStudentBatchAddInDto();
            for (int i=0;i<item.size();i++){
                if(item.size()>0&& !StringUtils.isEmpty(item.get(0))){
                    //设置学生姓名
                    bizStudentBatchAddInDto.setStuName(item.get(0));
                }
                if(item.size()>1&& !StringUtils.isEmpty(item.get(1))){
                    //截取括号里面的班级id
                    String s = item.get(1);
                    String substring = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
                    bizStudentBatchAddInDto.setEduClassId(Long.parseLong(substring));
                }
                if(item.size()>2&& !StringUtils.isEmpty(item.get(2))){
                    //设置学生性别
                    String sex = item.get(2).split("-")[1];
                    bizStudentBatchAddInDto.setSex(Integer.parseInt(sex));
                }
                if(item.size()>3&& !StringUtils.isEmpty(item.get(3))){
                    try {
                        //设置出生年月
                        Date date=dateFormat.parse(item.get(3));
                        bizStudentBatchAddInDto.setBirthdate(date);
                    } catch (ParseException e) {
                        log.error(item.get(0)+"同学出生时间格式错误!",e);
                    }
                }
                if(item.size()>4&& !StringUtils.isEmpty(item.get(4))){
                    try {
                        //设置入读时间
                        Date dates=dateFormat.parse(item.get(4));
                        bizStudentBatchAddInDto.setActivedate(dates);
                    } catch (ParseException e) {
                        log.error(item.get(0)+"同学入读时间格式错误!",e);
                    }
                }
                if(item.size()>5&& !StringUtils.isEmpty(item.get(5))){
                    //设置入读状态
                    String ss=item.get(5).split("-")[1];
                    bizStudentBatchAddInDto.setActive(Integer.parseInt(ss));
                }
                if(item.size()>6&& !StringUtils.isEmpty(item.get(6))){
                    //设置备注
                    bizStudentBatchAddInDto.setRemark(item.get(6));
                }
                if(item.size()>7&& !StringUtils.isEmpty(item.get(7))){
                    //设置手机号码
                    bizStudentBatchAddInDto.setParentIphone(item.get(7));
                }
                if(item.size()>8&& !StringUtils.isEmpty(item.get(8))){
                    //设置家长姓名
                    bizStudentBatchAddInDto.setParentName(item.get(8));
                }
                if(item.size()>9&& !StringUtils.isEmpty(item.get(9))){
                    //设置是否业主
                    bizStudentBatchAddInDto.setIsOwner(Integer.parseInt(item.get(9).split("-")[1]));
                }
                if(item.size()>10&& !StringUtils.isEmpty(item.get(10))){
                    //设置地址
                    bizStudentBatchAddInDto.setAddress(item.get(10));
                }
            }
            list.add(bizStudentBatchAddInDto);
        });
        return list;
    }

写的不算太好,有问题可以问我

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值