easyui,springmvc,poi实现上传excel写入数据到数据库中

上传excel文件操作数据有两种方式,分别是poi和jxl。但是jxl对高版本的excel(.xlsx)无法提供支持,所以本文使用poi实现。
前端使用easyui实现,控制层使用流行框架springmvc.

所需要的jar包:
poi-3.17jar,
poi-ooxml-3.17jar,
poi-ooxml-schemal-3.17jar,
xbean.jar


jsp代码:

<form id="indicatorAddExcelForm" method="post" enctype="multipart/form-data">
			<table class="grid">
			  <tr>
                <td>请选择Excel文件</td>            
                <td><input type="file" class="easyui-validatebox" id="upfile" name="upfile"></td> 
                             
              </tr>             
        	</table>  
		</form>

js代码:

注意:js代码主要是表明springmvc请求路径,其他代码可能是从项目里面拿出来的,仅作参考。前端页面以及js可参考其他。

<script type="text/javascript">
	$(function() 
	{
		$('#indicatorAddExcelForm').form(
		{
			url : '${pageContext.request.contextPath}/selfevaluation/addExcel',
			onSubmit : function() 
			{			  
				progressLoad();
				var isValid = $(this).form('validate');
				if (!isValid) 
				{
					progressClose();
				}
				return isValid;
			},
			success : function(result) 
			{			    
				progressClose();
				result = $.parseJSON(result);			
				if (result.success) 
				{		
				    parent.$.messager.alert('成功', result.msg, 'info');		  
				    parent.$.modalDialog.handler.dialog('close');
				} else 
				{
					parent.$.messager.alert('错误', result.msg, 'error');
				}
			}
		});
	});
</script>
springmvc代码:
 
   
	@RequestMapping("/addExcel")
	@ResponseBody
	public Json addExcel(HttpSession session,HttpServletRequest request) 
	{
		List<Indicator> inds=new ArrayList<Indicator>();//创建保存数据的list
		Json jj = new Json();				
		try
		{			 	      
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		    //输入流  
		    InputStream in =null;
		    MultipartFile file = multipartRequest.getFile("upfile"); 
		    if(file.isEmpty())
		    {  
		    	jj.setSuccess(false);
				jj.setMsg("文件不存在!");
				return jj;
		    }
		    String filename=file.getOriginalFilename();
		    in = file.getInputStream(); 
		    //得到excel  
		    Workbook wb = null;
		    String fileType = filename.substring(filename.lastIndexOf("."));  
		    if((".xls").equals(fileType))
		    {  
		        wb = new HSSFWorkbook(in);  //2003-  
		    }else if((".xlsx").equals(fileType))
		    {  
		       wb = new XSSFWorkbook(in);  //2007+  
		    }else
		    {  
		    	jj.setSuccess(false);
				jj.setMsg("文件格式错误!");
				return jj;
		    }   		  
		    //得到sheet  
		    Sheet sheet = wb.getSheetAt(0); //默认取第一个sheet 	         
		    //int colsNum = sheet.getPhysicalNumberOfRows();  //获取实际的行数	       
		    int rowsNum = sheet.getLastRowNum();//  	        	          
		    for(int j=1; j<rowsNum+1;j++) //第一行为表头,所以从第二行开始
		    {// getLastRowNum,获取最后一行的行标
		        Row row =sheet.getRow(j);
		        if (row != null) 
		        {
		        	Indicator ind=new Indicator();
		        	ind.setIndicator_itemid(row.getCell(0).toString());
		        	ind.setDept_result(row.getCell(1).toString());
		        	ind.setDept_remark(row.getCell(2).toString());
		        	inds.add(ind);
		            /*for (int k = 0; k < row.getLastCellNum(); k++) 
		            {// getLastCellNum,是获取最后一个不为空的列是第几个	                       
		                System.out.print(row.getCell(k) + "\t");	                      
		            }*/
		        }
		              
		    }
		    //System.out.println(inds);
		    wb.close();	  
		 } catch (IOException e) 
	     {  
		      e.printStackTrace();  
		 }
		//获取登陆用户的id
		SessionInfo sessionInfo=(SessionInfo)session.getAttribute(GlobalConstant.SESSION_INFO);
		selfEvaluationService.addExcel(sessionInfo.getId(),inds);
		jj.setSuccess(true);
		jj.setMsg("添加成功!");
		return jj;
	}


最后,别忘了在spring-mvc.xml文件中加入配置,如果已经配置过,忽略即可。
<!-- 上传文件控制 -->
<bean id="multipartResolver"  
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 设置上传文件的最大尺寸为10MB -->  
    <property name="maxUploadSize">  
        <value>10485760</value>  
    </property> 
     
</bean>



猜你喜欢

转载自blog.csdn.net/qq_20372833/article/details/79423083