导入excel,对excel数据验证

//数据库中测评id
		List listIdFromDB=exchangeCourseDetailsServiceImpl.getTestId();
		//数据库中已存在的账号
		List listAccountFromDB=exchangeCourseDetailsServiceImpl.getTestAccount();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("upoadFileName");

		// 获得文件名:
		String realFileName = file.getOriginalFilename();
		System.out.println("获得文件名:" + realFileName);
		// 获取路径
		String ctxPath = request.getContextPath();
		ctxPath = request.getSession().getServletContext().getRealPath("/")
				+ "uploads\\exchangeCourse\\";
		System.out.println("路径:" + ctxPath);
		// 创建文件
		File dirPath = new File(ctxPath);
		if (!dirPath.exists()) {
			dirPath.mkdir();
		}

		// 构建随机文件名
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
		String dateFileName = format1.format(new Date());
		// 随机文件名
		String newFileName = ctxPath + dateFileName + realFileName;
		File uploadFile = new File(newFileName);
		FileCopyUtils.copy(file.getBytes(), uploadFile);


		jxl.Workbook rwb = Workbook.getWorkbook(file.getInputStream());
		Sheet rs = rwb.getSheet(0);
		Cell[] cell = rs.getRow(0);
		int length = cell.length;
		//列名与列标映射
		Map keyMap = null;
		if (length > 0) {
			keyMap = new HashMap();
			for (int i = 0; i < length; i++) {
				String columnName = cell[i].getContents().trim();
				if (columnName != null) {
					keyMap.put(columnName, i);
				}
			}
		}

		//验证有效列数
		int idIndex=-1;
		int accountIndex=-1;
		int passwordIndex=-1;
		
		if(cell.length>3){
			request.setAttribute("errorMsg","上传表格的列数不符合要求,请参照模版!");
			return list(modelMap, request, sessionUserData);
		}
		
		try{
			idIndex=keyMap.get("测评类ID");
			accountIndex=keyMap.get("账号");
			passwordIndex=keyMap.get("密码");
		}catch(Exception e){
			e.printStackTrace();
			if(idIndex==-1){
				request.setAttribute("errorMsg","缺少测评类ID这一列");
				return list(modelMap, request, sessionUserData);
			}
			if(accountIndex==-1){
				request.setAttribute("errorMsg","缺少账户这一列");
				return list(modelMap, request, sessionUserData);
			}
			if(passwordIndex==-1){
				request.setAttribute("errorMsg","缺少密码这一列");
				return list(modelMap, request, sessionUserData);
			}
			return list(modelMap, request, sessionUserData);
		}


		Cell[] idCells = rs.getColumn(idIndex);//测评类id列

		Cell[] accountCells = rs.getColumn(accountIndex);//账号列
		Cell[] accountCellsTemp=accountCells; //账号列副本

		Cell[] passwordCells = rs.getColumn(passwordIndex);//密码列
		
		//逐行验证数据有效性
		for(int i=1;i 
  

 

你可能感兴趣的:(JavaCode)