JAVA POI批量导入EXCEL数据到数据库

首先先记录下碰到的问题: 

原先想直接传要上传的文件路径到后端,然后后端绝对定位到相应文件进行数据的解析,后面发现浏览器这边为了安全问题,是不能获得文件的真实路径的,只能获得一个虚假的路径,然后这种做法就行不通了,我的解决方法是先把文件上传的到后端相关目录,解析完数据后在将对应的文件删除


下面贴代码:

	        		<form id="monitordocform" enctype="multipart/form-data" style="padding-top: 10px;" action="monitor/excelData">
	                        <div class="file-input file-input-new">
	                        <div class="file-preview ">
	    						<div class="close fileinput-remove">×</div>
	    							<div class="file-drop-disabled">
						    <div class="file-preview-thumbnails">
						    </div>
						    <div class="clearfix"></div>    
						    <div class="file-preview-status text-center text-success"></div>
						    <div class="kv-fileinput-error file-error-message" style="display: none;"></div>
						    </div>
						</div>
						<div class="kv-upload-progress hide"><div class="progress">
						    <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%;">
						        0%
						     </div>
						</div></div>
						
						<div class="input-group file-caption-main">
						   <div tabindex="500" class="form-control file-caption  kv-fileinput-caption">
						   <div class="file-caption-name" id="monitordocpath"></div>
						</div>
						
						   <div class="input-group-btn" >
						       <button type="button" tabindex="500" title="Clear selected files" class="btn btn-default fileinput-remove fileinput-remove-button"><i class="glyphicon glyphicon-trash"></i>  <span class="hidden-xs">移除</span></button>
						       <button type="button" tabindex="500" title="Abort ongoing upload" class="btn btn-default hide fileinput-cancel fileinput-cancel-button"><i class="glyphicon glyphicon-ban-circle"></i>  <span class="hidden-xs">取消</span></button>
						       <button type="submit" tabindex="500" title="Upload selected files" class="btn btn-default fileinput-upload fileinput-upload-button">
						       <i class="glyphicon glyphicon-upload"></i>  <span class="hidden-xs">上传</span></button>
						       <div tabindex="500" class="btn btn-primary btn-file" style="background-color: #0093DF;">
							       <i class="glyphicon glyphicon-folder-open"></i>   
							       <span class="hidden-xs">选择文件</span>
							       <input  type="file" id="monitordoc" name="monitordoc" οnchange="showPath(this)">
						       </div>
						   </div>
						</div>
						</div>
						
	                    <br>
		        		<div class="uploadtips">提示:请上传您要分发的图斑数据,格式.xls/.xlsx </div>  
                    </form>
传输文件 form表单要加上 
enctype="multipart/form-data" 

这个属性,

JS中AJAX上传文件的格式:

function excelData(){
	var monitordocpath=$("#monitordocpath").text();
	if(monitordocpath!=null && monitordocpath!=""){
		var form = new FormData(document.getElementById("monitordocform"));
		$.ajax({
		    url:  "monitor/excelData",
		    type: 'POST',
		    data: form,
		    processData: false,
		    contentType : false,
		    success:function(data){
		    	alert(data);
		    	if(data=="true" || data==true){
		    		$("#monitorspotgrid").mtable("reload");
		    		closeMonitorUploadWin();
		    		$.mal({
						text : '导入成功',
						type : 'success' 
					});
		    	}else{
		    		$.mal({
						text : '导入失败',
						type : 'error'
					});
		    	}
            },
            error:function(e){
             
            }
		})
		
	
	}else{
		$.mal({
			text : '请先选择文件',
			type : 'warning'
		});
	}
}

JAVA后台代码的处理方法:

@ResponseBody
	@RequestMapping(value="excelData",method = RequestMethod.POST)
	public String excelData(HttpServletRequest request,HttpServletResponse response,@RequestParam("monitordoc")MultipartFile monitordoc){
    	// 上传文件路径
		String path = request.getSession().getServletContext().getRealPath("/upload/");
		System.out.println(path);
		// 上传文件名
		String fileName = monitordoc.getOriginalFilename();
		if(fileName.endsWith("xls") || fileName.endsWith("xlsx")){
		File file=new File(path+File.separator+fileName);
		ShardedJedisProvider jedis=JedisManager.getShardedJedis("redis"); //根据需要获取相关数据
		String sessionId = GetSessionID(request, response);
		String tenantId = jedis.hget("userkey:"+sessionId, "tenantId");
		try {
			monitordoc.transferTo(file);//先将上传的文件保存
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<PdaOneMapMonitorSpotModel>list=paseExcel(file,tenantId,fileName);//解析上传的Excel数据
		Integer result=pdaOneMapMonitorSpotService.batchInsert(list);
		if (result>0) {
			 return "true";
		}else {
			return  "false";
		}
		}else {
			return "false";
		}
      }
	

解析Excel数据的方法

	public List<PdaOneMapMonitorSpotModel> paseExcel(File f,String tenantId,String fileName){
			String path=f.getPath();
			List<PdaOneMapMonitorSpotModel>list=new ArrayList<PdaOneMapMonitorSpotModel>();
			FileInputStream fis =null;
			Map<String, Object>map=new HashMap<String, Object>();
	        Workbook wookbook = null;
	        //XSSFWorkbook ss=null;
	        int flag = 0;
	        
	        try{
	            //获取一个绝对地址的流
	              fis = new FileInputStream(f);
	        }
	        catch(Exception e){
	        	deleteExcel(path);
	            e.printStackTrace();
	        }
	       
	        try {
				if(fileName.endsWith("xls")){
					 //2003版本的excel,用.xls结尾
					  wookbook = new HSSFWorkbook(fis);//得到工作簿
				}else {
					 //2007版本的excel,用.xlsx结尾                 
	                   wookbook = new XSSFWorkbook(fis);//得到工作簿
				}
	          
	        }  catch (Exception ex) {        	 
	        	ex.printStackTrace();
	        	 deleteExcel(path);
	        }
	        
	        //得到一个工作表
	        Sheet sheet = wookbook.getSheetAt(0);
	        
	        //获得表头
	        Row rowHead = sheet.getRow(0);
	        
	      //根据不同的data放置不同的表头
	        Map<Object,Integer> headMap = new HashMap<Object, Integer>(); 
	        
	        try{
	            //----------------这里根据你的表格有多少列
	            while (flag < rowHead.getPhysicalNumberOfCells())
	            {
	                Cell cell = rowHead.getCell(flag);
	                if (getRightTypeCell(cell).toString().equals("标识码"))
	                {
	                    headMap.put("bsm", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("监测编号"))
	                {
	                    headMap.put("jcbh", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("图斑类型"))
	                {
	                    headMap.put("tblx", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("监测面积(亩)"))
	                {
	                    headMap.put("jcmj", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("变更后地类"))
	                {
	                    headMap.put("bghdl", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("变更范围情况"))
	                {
	                    headMap.put("bgfwqk", flag);
	                }
	                
	                if (getRightTypeCell(cell).toString().equals("未变更原因"))
	                {
	                    headMap.put("wbgyy", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("备注"))
	                {
	                    headMap.put("bz", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("接收人员"))
	                {
	                    headMap.put("jsry", flag);
	                }
	                if (getRightTypeCell(cell).toString().equals("分发状态"))
	                {
	                    headMap.put("ffzt", flag);
	                }
	                
	                flag++;
	            }
	        } catch (Exception e){
	        	deleteExcel(path);
	            e.printStackTrace();
	            System.out.println("表头不合规范,请修改后重新导入");
	        }
	        
	        
	        //获得数据的总行数
	        int totalRowNum = sheet.getLastRowNum();
	        
	        if(0 == totalRowNum){
	            System.out.println("Excel内没有数据!");
	        }
	        
	        Cell cell_1 = null,cell_2 = null; Cell cell_3 = null,cell_4 = null; Cell cell_5 = null,cell_6 = null; 
	        Cell cell_7 = null,cell_8 = null;Cell cell_9 = null,cell_10 = null;
	       //获得所有数据
	        for(int i = 1 ; i <= totalRowNum ; i++){
	            //获得第i行对象
	            Row row = sheet.getRow(i);
		        PdaOneMapMonitorSpotModel pdaOneMapMonitorSpotModel=new PdaOneMapMonitorSpotModel();
	            try{
	                cell_1 = row.getCell(headMap.get("bsm"));
	                cell_2 = row.getCell(headMap.get("jcbh"));
	                cell_3 = row.getCell(headMap.get("tblx"));
	                cell_4 = row.getCell(headMap.get("jcmj"));
	                cell_5 = row.getCell(headMap.get("bghdl"));
	                cell_6 = row.getCell(headMap.get("bgfwqk"));
	                cell_7 = row.getCell(headMap.get("wbgyy"));
	                cell_8 = row.getCell(headMap.get("bz"));
	                cell_9 = row.getCell(headMap.get("jsry"));
	                cell_10 = row.getCell(headMap.get("ffzt"));
	            } catch (Exception e){
	                e.printStackTrace();
	                System.out.println("获取单元格错误");
	            	deleteExcel(path);
	            }
	            
	            try{
	                pdaOneMapMonitorSpotModel.setMonitorNum((String)getRightTypeCell(cell_2));
	                pdaOneMapMonitorSpotModel.setMapType((String)getRightTypeCell(cell_3));
	                pdaOneMapMonitorSpotModel.setMonitorArea((String)getRightTypeCell(cell_4));
	                pdaOneMapMonitorSpotModel.setChangeClass((String)getRightTypeCell(cell_5));
	                pdaOneMapMonitorSpotModel.setChangeRange((String)getRightTypeCell(cell_6));
	                pdaOneMapMonitorSpotModel.setCause((String)getRightTypeCell(cell_7));
	                pdaOneMapMonitorSpotModel.setRemark((String)getRightTypeCell(cell_8));
	                if (cell_10.equals("已分发")) {
		                pdaOneMapMonitorSpotModel.setDistributeStatus("1");
					}else{
						 pdaOneMapMonitorSpotModel.setDistributeStatus("0");
					}
	                pdaOneMapMonitorSpotModel.setTenantId(tenantId);
	                list.add(pdaOneMapMonitorSpotModel);
	                
	            } catch (ClassCastException e){	
	            	deleteExcel(path);
	                e.printStackTrace();
	            }
	        }
	    	deleteExcel(path);
	        return list;
	        
	}

解析成功或者出现异常的情况下都将上传的文件删除,调用deleteExcel方法

/**
	 * 删除指定路径下的Excel
	 * @param path
	 * @return
	 */
	public String deleteExcel(String path){

		 try {
			 //目录路径
		   	 File target=new File(path);
			 //删文件
			 target.delete();
		} catch (Exception e) {
			return "false";
		}
		return "true";
	}

返回单元格数据类型的函数:

 /**
     *     
     * @param cell 一个单元格的对象
     * @return 返回该单元格相应的类型的值
     */
    public static Object getRightTypeCell(Cell cell){
    
        Object object = null;
        switch(cell.getCellType())
        {
            case Cell.CELL_TYPE_STRING :
            {
                object=cell.getStringCellValue();
                break;
            }
            case Cell.CELL_TYPE_NUMERIC :
            {
                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                object=cell.getNumericCellValue();
                break;
            }
                
            case Cell.CELL_TYPE_FORMULA :
            {
                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                object=cell.getNumericCellValue();
                break;
            }
            
            case Cell.CELL_TYPE_BLANK :
            {
                cell.setCellType(Cell.CELL_TYPE_BLANK);
                object=cell.getStringCellValue();
                break;
            }
        }
        return object;
    }    

暂时就这样解决,如果有能够不用保存先保存文件到服务器就能够解析要上传文件的数据的方法的话,欢迎大神指教!

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值