POI导入EXCEL数据到数据库

1、前台页面,如下图所示,注意划红线区域不要写错,尤其是form表单,enctype="multipart/form-data" 不要忘写

 

2. 后台Controller

@RequestMapping("import-employee")
	public String importEmployee(EmployeeModel eQuery,
			 @RequestParam("file") MultipartFile file) {
		List<EmployeeModel> emp= new ArrayList<EmployeeModel>();
		if (!file.isEmpty()) {
			String extent = importEmployeeService.getExtensionName(file
					.getOriginalFilename());   //获取文件后缀名 getExtensionName 后文有介绍继续往下看
			if (StringUtil.isEmpty(extent)) {
				return "redirect:student-manage.htm";
			}
			String tempFileName = (new Date()).getTime() + "." + extent;  //生成随机新的文件名,主要避免缓存带来的干扰
			File temp = new File(tempFileName);  
			try {
				temp.createNewFile(); //创建新文件
                                file.transferTo(temp);//将上传文件写入服务器指定文件
                        } catch (IOException e1) {
	                    logger.error(e1.getMessage());
                        }try {
	                        emp = importEmployeeService.getEmployeeInfomation(temp); //用来读取excel中的数据,并插入到数据库
                        } catch (Exception e) {
	                    return "redirect:student-manage.htm";
                        }if (temp.exists()) {
	                    temp.delete(); //删除临时文件
                        }
                    }
                        return "redirect:student-manage.htm";
            }

获取后缀名方法

public   String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

核心部分

public List<EmployeeModel> getEmployeeInfomation(File file) {

		Workbook wb = null;
		Row row = null;
		Row row2 = null;
		Sheet sheet = null;
		InputStream is = null;
		List<EmployeeModel> list;
		try {
			// 设置要读取的文件路径
			is = new FileInputStream(file);
			// 如果不支持标记、重置, 则包装它
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			// //创建工作薄,读取2003Excel和2007Excel
			// HSSFWorkbook相当于一个excel文件,HSSFWorkbook是解析excel2007之前的版本(xls)

			// 之后版本使用XSSFWorkbook(xlsx)
			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				wb = new XSSFWorkbook(OPCPackage.open(is));

			}
			is.close();
		} catch (IOException e) {
			error = "Read error for File format ";
			e.printStackTrace();
			return null;
		} catch (InvalidFormatException e2) {
			error = "文件读取错误请检查文件格式是否正确";
			e2.printStackTrace();
			return null;
		} catch (Exception e3) {
			error = "文件读取错误请检查文件格式是否正确";
			e3.printStackTrace();
			return null;
		}
		// 获取第一个工作薄
		sheet = wb.getSheetAt(0);
		list = new ArrayList<EmployeeModel>();
		// 获取总行数
		int sumRow = sheet.getLastRowNum();
		// 检查所有的行
		//int maxRow = ExcelConstants.MAX_ROWS;			
		// System.out.println("最大"+maxRow+"行、、、、、、、、、、、、、、、、、、、、、");
		if (sumRow <0) {
//			error = "工作表的行数不能大于" + maxRow + ",请重新设定导入数据的行数,分到几张表中再次导入!";
			return null;

		} 
		SimpleDateFormat pattFormat = new SimpleDateFormat("dd/MM/yyyy");
		if(sumRow>50){
			List<SystemItemConfigModel> emp = systemItemConfigMapper.getSystemItemResultByCode("ImportEmployeeNum");
			String empNum=null;
			if(emp!=null&&emp.size()>0){
				//	https://137.200.48.72:8443/upload
				  empNum=emp.get(0).getItem_name();
			}
			sumRow=Integer.parseInt(empNum); 
		}
		// 获得行(默认重 0开始)
		for (int i = 1; i <= sumRow; i++) {
			EmployeeModel model1 = new EmployeeModel();
			// 获取行
			row = sheet.getRow(i);
			// 如果整行不能为空 执行下列代码
			if (row.getCell(0) != null && row.getCell(1) != null) {
					model1.setEmployeeCode(getValue(row.getCell(1)));  //getValue 用来判断excel中的数据类型,例如时间进行格式化
					model1.setName(getValue(row.getCell(2)));
					... 此处省略一些字段,根据需要自行调整
					EmployeeModel employeeModel = employeeMapper.getByCode(model1.getEmployeeCode());
					if (employeeModel == null) {
						employeeMapper.insert(model1);
					}else{
						employeeMapper.updateEmployee(model1);
					}			
					list.add(model1);
				}

		}
		return list;
	}

	//解决excel类型问题,获得数值  
    public static String getValue(Cell cell) {  
        String value = "";  
        if(null==cell){  
            return value;  
        }  
        switch (cell.getCellType()) {  
        	//数值型  
        	case Cell.CELL_TYPE_NUMERIC:  
            if (HSSFDateUtil.isCellDateFormatted(cell)) {  
                //如果是date类型则 ,获取该cell的date值  
                Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());  
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                value = format.format(date);;  
            }else {// 纯数字  
                BigDecimal big=new BigDecimal(cell.getNumericCellValue());  
                value = big.toString();  
                //解决1234.0  去掉后面的.0  
                if(null!=value&&!"".equals(value.trim())){  
                     String[] item = value.split("[.]");  
                     if(1<item.length&&"0".equals(item[1])){  
                         value=item[0];  
                     }  
                }  
            }  
            break;  
            //字符串类型   
	        case Cell.CELL_TYPE_STRING:  
	            value = cell.getStringCellValue().toString();  
	            break;  
	        // 公式类型  
	        case Cell.CELL_TYPE_FORMULA:  
	            //读公式计算值  
	            value = String.valueOf(cell.getNumericCellValue());  
	            if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串  
	                value = cell.getStringCellValue().toString();  
	            }  
	            break;  
	        // 布尔类型  
	        case Cell.CELL_TYPE_BOOLEAN:  
	            value = " "+ cell.getBooleanCellValue();  
	            break;  
	        // 空值  
	        case Cell.CELL_TYPE_BLANK:   
	            value = "";  
	            break;  
	        // 故障  
	        case Cell.CELL_TYPE_ERROR:   
	            value = "";  
	            break;  
	        default:  
	            value = cell.getStringCellValue().toString();  
	    }  
	    if("null".endsWith(value.trim())){  
	        value="";  
	    }  
	    return value;  
    }  



猜你喜欢

转载自blog.csdn.net/apbbbbb/article/details/79726969