Excel批量导入(导出同理)

  • 在做JavaWeb中添加数据使我们在所难免会遇到的,在大数据的环境下批量添加和批量删除是必须的,而批量删除只需要获取到我们需要删除的ID就可以了,在批量添加中我们就会遇到问题,问题是得到批量的数据,这就涉及到了poi技术中的Excel导入导出
  • 在前端中我们使用的Dropzone上传技术,在BootStrap中使用模态框显示Dropzone界面
  • <div class="ibox-content">
    <form id="my-awesome-dropzone" class="dropzone"
    action="${pageContext.request.contextPath}/change/assistantUpload.action">
    <div class="dropzone-previews"></div>
    <button type="submit" class="btn btn-primary pull-right">提交</button>
    </form>
    </div>

  • Dropzone技术特点就是可以将温江拖拽到画面里面,然后开始js工作在form表单提交之后开始到后台收取数据

  • 在后台的函数上面加上如下标记 就可以保证范文到制定的函数了
  • 这里写图片描述
  • 然后我们需要制定上传的编码格式为UTF-8这里写图片描述
  • 下面就是后台数据处理的部分

    `try {
    // 上传得请求对象
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    // 获取上传的文件
    CommonsMultipartFile multipartFile = (CommonsMultipartFile) req
    .getFile(“upload”);
    // 获取文件的名称 xxx.jpg xxx_1000101897.jp
    String fileName = multipartFile.getOriginalFilename();
    String suffix = fileName.substring(fileName.lastIndexOf(“.”));
    // 声明excel文件对象
    Workbook wb = null;
    // 获取文件上传输入流对象
    InputStream is = multipartFile.getInputStream();
    // 判断文件的后缀名称
    if (“.xls”.equalsIgnoreCase(suffix)) {
    wb = new HSSFWorkbook(is);
    } else if (“.xlsx”.equalsIgnoreCase(suffix)) {
    wb = new XSSFWorkbook(is);
    }

        // 存储的班级名称
        List<String> clazzNames = new ArrayList<String>();
        // 存储的学号
        List<String> studnos = new ArrayList<String>();
        // 判断是否为null
        if (wb != null) {
            // 读取内容
            Sheet sheet = wb.getSheetAt(0);
            List<StudentCustom> students = new ArrayList<StudentCustom>();
            // 读取行数
            int rowNumber = sheet.getPhysicalNumberOfRows();
            // 遍历行数
            for (int row = 1; row < rowNumber; row++) {
                StudentCustom student = new StudentCustom();
                // 获取一行记录对象
                HSSFRow entity = (HSSFRow) sheet.getRow(row);
                // 获取列数
                int colNumber = entity.getPhysicalNumberOfCells();
                // 遍历列数
                for (int col = 0; col < colNumber; col++) {
                    // 获取指定列
                    HSSFCell cell = entity.getCell(col);
                    // 声明当前列的值
                    String value = "";
                    Date date = null;
                    // 判断是否为null
                    if (cell != null) {
                        // 判断单元格类型
                        switch (cell.getCellType()) {
                        // 数字类型
                        case Cell.CELL_TYPE_NUMERIC:
                            // 判断是否是日期类型
                            if (HSSFDateUtil.isCellDateFormatted(cell)) { // 日期类型
                                SimpleDateFormat sdf = new SimpleDateFormat(
                                        "yyyy-MM-dd");
                                date = HSSFDateUtil.getJavaDate(cell
                                        .getNumericCellValue());
    
                            } else {
                                // 获取数字
                                Integer data = (int) cell
                                        .getNumericCellValue();
                                if (col == 1) {
                                    HSSFCellStyle cellStyle = cell
                                            .getCellStyle();
                                    String format = cellStyle
                                            .getDataFormatString();
                                    DecimalFormat f = new DecimalFormat(
                                            format);
                                    value = f.format(data);
                                } else {
                                    value = data.toString();
                                }
                            }
                            break;
                        // 判断是否是字符型
                        case Cell.CELL_TYPE_STRING:
                            value = cell.getStringCellValue();
                            break;
                        // 判断是否是boolean型
                        case Cell.CELL_TYPE_BOOLEAN:
                            Boolean data = cell.getBooleanCellValue();
                            value = data.toString();
                            break;
                        // 错误类型
                        case Cell.CELL_TYPE_ERROR:
                            // System.out.println("单元格内容出现错误");
                            value = "error";
                            break;
                        // 判断是否是公式类型
                        case Cell.CELL_TYPE_FORMULA:
                            value = String.valueOf(cell
                                    .getNumericCellValue());
                            if (value.equals("NaN")) {// 如果获取的数据值非法,就将其装换为对应的字符串
                                value = cell.getStringCellValue()
                                        .toString();
                            }
                            break;
                        case Cell.CELL_TYPE_BLANK:
                            // System.out.println("单元格内容 为空值 ");
                            value = null;
                            break;
                        default:
                            value = cell.getStringCellValue().toString();
                            break;
                        }
    
                        //System.out.println(value);
    
                        if (col == 1) {
                            studnos.add(value);
                            student.setStudno(value);
                            // 默认密码
                            student.setPass(value);
                        } else if (col == 2) {
                            student.setName(value);
                        } else if (col == 3) {
                            student.setSex(value);
                        } else if (col == 4) {
                            student.setEnrol(date);
                        } else if (col == 5) {
                            student.setEmail(value);
                        } else if (col == 6) {
                            if (!clazzNames.contains(value)) {
                                clazzNames.add(value);
                            }
                            // 查询设置班级的id值
                            Clazz clazz = new Clazz();
                            clazz.setName(value);
                            student.setClazz(clazz);
                        }
                    }
    
                }
                // 行结束
                students.add(student);
            }
    
            // 第一步检测班级是否存在
            // 查询出该用户管理的班级
            List<Clazz> clazzs = clazzService.selectByAssistanUserId(user
                    .getId());
            // 班级的名称集合
            List<String> names = new ArrayList<String>();
            // 遍历班级
            for (Clazz clz : clazzs) {
                // 把班级名称加入到集合中
                names.add(clz.getName());
            }
            // 遍历excel中存在的班级
            for (String clazzName : clazzNames) {
                //System.out.println(clazzName);
                // 判断excel中的班级是否 存在班级集合中
                if (!names.contains(clazzName)) {
                    throw new ClazzExitException("该用户不负责班级,或者班级不存在");
                }
            }
    
            // 第二步检测学号是否存在
            QueryVo vo = new QueryVo();
            int count = studentService.selectAdminStudentsCount(vo);
            vo.setStartSize(0);
            vo.setPageSize(count);
            // 查询出所有学生信息
            List<StudentCustom> stus = studentService.selectAdminStudents(vo);
    
            List<String> nos = new ArrayList<String>();
            // 遍历studnos学号,
            for (StudentCustom stu : stus) {
                // 把班级名称加入到集合中
                nos.add(stu.getStudno());
            }
            // 1.1如果excel中有重复的学号,也不可以插入 扩展
            for(int i =0;i<studnos.size();i++){
                for(int j=i+1;j<studnos.size();j++){
                    if(studnos.get(i)==studnos.get(j)){
                        throw new ExcelStuNoExitException(studnos.get(i)+"该学号在Excel存在重复");
                    }
                }
            }
            // 检测查询的学号中是否含有该班级,如果含有 就跑出异常
            for (String no : nos) {
                System.out.println(no);
                // 判断excel中的班级是否 存在班级集合中
                if (studnos.contains(no)) {
                    System.out.println(no);
                    throw new StuNoExitException(no+"学号已存在");
                }
            }
    
            // excel解析结束
            // 按班级分好类
            Map<Clazz, List<StudentCustom>> map = new HashMap<Clazz, List<StudentCustom>>();
            // 批量保存学生信息
    
            for (String clazzName : clazzNames) {
                List<StudentCustom> s = new ArrayList<StudentCustom>();
                Clazz clazz = clazzService.selectClazzName(clazzName);
                for(int i=0;i<students.size();i++){
                    if(students.get(i).getClazz().getName()==clazzName)
                    {
                        students.get(i).setClazzId(clazz.getId());
                        s.add(students.get(i));
                    }
                }
                map.put(clazz, s);
            }
            transactionService.insertStudentsCustomFromExcel(map);
            // 同步更新班级的人数
    
        }
    
        out.print("{"msg":"success"}");
    } catch (ClazzExitException ce) {
        out.print("{"msg":""+ce+""}");
    } catch (ExcelStuNoExitException ce) {
        out.print("{"msg":""+ce+""}");
    } catch (StuNoExitException ce) {
        out.print("{"msg":""+ce+""}");
    } catch (Exception ex) {
        out.print("{"msg":""+ex+""}");
    } finally {
        out.flush();
        out.close();
    
  • 另外值得一提的是在前端我们的需要因要到一段js来设置传送的接口
  • `function initUploadOptions(){
    Dropzone.options.myAwesomeDropzone = {
    method : ‘post’,
    paramName : ‘upload’,
    autoProcessQueue : false,
    uploadMultiple : false,
    maxFiles : 1,
    init : function() {
    var myDropzone = this;
    this.element.querySelector(“button[type=submit]”)
    .addEventListener(“click”, function(e) {
    e.preventDefault();
    e.stopPropagation();
    myDropzone.processQueue()
    });
    this.on(“sending”, function() {
    alert(“发送过程中”);
    });
    this.on(“success”, function(file, response) {
    alert(file + “成功” + response);
    var obj=eval(“(“+response+”)”);
    file.previewTemplate.appendChild(document
    .createTextNode(obj.msg));
    window.location.reload(true);
    });
    this.on(“error”, function(file, response) {
    alert(file + “失败” + response);
    })
    }
    }

    };`

  • 在这里我们需要制定参数的名称为upload 这样我们在controller中渠道upload这个上传的对象 整个过程就可以将Excel中的数据拿到了,至于怎么存取就看个人了,你可以用list去接收这些数据
  • 上面这些就是为了实现功能,读者可以自行在此基础上进行分装方法放在自己的项目上就可以使用了
  • 在此之前我还有一种方法是封装在Util工具类中的 至于这点我就不多说了我放在下载里 有需要的朋友自己下载吧
  • http://download.csdn.net/detail/u013132051/9561129
原文地址:https://www.cnblogs.com/zhangxinhua/p/8319251.html