java实现excel导入数据到数据库,支持xls和xlsx

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QCIWYY/article/details/83024591

前端代码此处忽略,如需请参考本人上传txt博客模板,

上传txt博客地址:https://blog.csdn.net/QCIWYY/article/details/82758097

废话不多说直接上代码。

/**
	 * 批量新增词条(上传excel文件)
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping(value = "/uploaData")
	public BaseResponse<T> uploaData(HttpServletRequest request){
		BaseResponse<T> result = new BaseResponse<T>();
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		MultipartFile mf = multipartHttpServletRequest.getFile("file");
		int rowNumber = 0;
		try {
			byte[] content = mf.getBytes();
            //文件放置本地
			String filePath = getFilePath(mf);
			FileOutputStream outputStream = new FileOutputStream(filePath);
			outputStream.write(content);
			outputStream.close();
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
			    //数据插入数据库
            	rowNumber = uploadFile(filePath);
            	new File(filePath).delete();
            	if(rowNumber > 0 ) {
            		result.code = 200;
                    result.setMsg("导入完成,共导入"+rowNumber+"个词条!");
            	}else {
            		result.code = 403;
                    result.setMsg("导入失败,词条重复!");
            	}
                
		    }else{
		    	log.info("找不到指定的文件");
		    }
		} catch (Exception e) {
			e.printStackTrace();
			 result.code = 500;
	         result.setMsg("导入失败,服务器错误!");
		}
		return result;
	}
	
	private String getFilePath(MultipartFile file) {
		String guid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
		String fileName = file.getOriginalFilename();
		String extName = fileName.substring(fileName.lastIndexOf("."));
		String fileNameWithoutExt = fileName.replaceAll(extName, "");
		String fileNewName = fileNameWithoutExt + "-" + guid + extName;
		String filePath = fileUploadConfig.getSavePath() + fileNewName;
		System.out.println("filePath" + filePath);
		return filePath;
	}
	
	public int uploadFile(String filePath) throws Exception {
		int rowNumber = 0;
		InputStream is = new FileInputStream(filePath);
		Workbook workbook = null;  
        try {  
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象  
            if(filePath.endsWith(".xls")){  
                //2003  
                workbook = new HSSFWorkbook(is);  
            }else if(filePath.endsWith(".xlsx")){  
                //2007  
                workbook = new XSSFWorkbook(is);  
            }  
        } catch (IOException e) {  
            log.info(e.getMessage());  
        }
        
        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回  
	    if(workbook != null){  
	        for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
	            //获得当前sheet工作表  
	            Sheet sheet = workbook.getSheetAt(sheetNum);  
	            if(sheet == null){  
	                continue;  
	            }  
	            //获得当前sheet的开始行  
	            int firstRowNum  = sheet.getFirstRowNum();  
	            //获得当前sheet的结束行  
	            int lastRowNum = sheet.getLastRowNum();  
	            //循环除了第一行的所有行  
	            for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){  
	                //获得当前行  
	                Row row = sheet.getRow(rowNum);  
	                if(row == null){  
	                    continue;  
	                }  
	                //获得当前行的开始列  
	                int firstCellNum = row.getFirstCellNum();  
	                //获得当前行的列数  
	                int lastCellNum = row.getPhysicalNumberOfCells();  
	                String[] cells = new String[row.getPhysicalNumberOfCells()]; 
	                Student student = new Student();
	                //循环当前行  
	                for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
	                    Cell cell = row.getCell(cellNum);  
	                    cells[cellNum] = getCellValue(cell); 
	                    System.out.println(cell.toString());
	                    if(cellNum == 0) {
	                    	student.name = cell.toString();
	                    }else if(cellNum == 1) {
	                    	student.sex = cell.toString();
	                    }else if(cellNum == 2) {
	                    	student.age = cell.toString();
	                    }
	                } 
	                Student wt = StudentManager.Add(student);
	                if(wt != null) {
        		    	log.info("保存成功!");
        		    	rowNumber++;
        		    }else {
        		    	log.info("保存失败!");
        		    }
	                
	            }  
	        }  
	        workbook.close();
	        is.close();
	    }  
		return rowNumber;
	}
	
	public static String getCellValue(Cell cell){  
        String cellValue = "";  
        if(cell == null){  
            return cellValue;  
        }  
        //把数字当成String来读,避免出现1读成1.0的情况  
        if(cell.getCellTypeEnum() == CellType.NUMERIC){  
            cell.setCellType(CellType.STRING);  
        }  
        //判断数据的类型  
        switch (cell.getCellTypeEnum()){  
            case NUMERIC: //数字  
                cellValue = String.valueOf(cell.getNumericCellValue());  
                break;  
            case STRING: //字符串  
                cellValue = String.valueOf(cell.getStringCellValue());  
                break;  
            case BOOLEAN: //Boolean  
                cellValue = String.valueOf(cell.getBooleanCellValue());  
                break;  
            case FORMULA: //公式  
                cellValue = String.valueOf(cell.getCellFormula());  
                break;  
            case BLANK: //空值   
                cellValue = "";  
                break;  
            case ERROR: //故障  
                cellValue = "非法字符";  
                break;  
            default:  
                cellValue = "未知类型";  
                break;  
        }  
        return cellValue;  
    }  

猜你喜欢

转载自blog.csdn.net/QCIWYY/article/details/83024591