java導入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;  
    }  

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章