欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

excel文件上传前后端方法

程序员文章站 2024-03-20 14:42:34
...

excel文件上传-原始方法

1.原生的上传方法

<div class="layui-upload">
                    <input type="file" id="myfile" name="fileInput" style="display: inline" />
                     <input class="btn btn-primary btn-sm" style="padding-left:50px;padding-right: 50px;margin-top:10px;" type="button" value="上传" onclick="check();"> 
                         </div>

这里上传事件比较多,可根据业务需要在相应事件上写逻辑代码

  function upload() {
      // 1.准备FormData
      var fd = new FormData();
      fd.append("fileInput", $("#myfile")[0].files[0]);
      // 创建xhr对象
      var xhr = new XMLHttpRequest();
      // 监听状态,实时响应
      // xhr 和 xhr.upload 都有progress事件,xhr.progress是下载进度,xhr.upload.progress是上传进度
      xhr.upload.onprogress = function(event) {
    /*       if (event.lengthComputable) {
              var percent = Math.round(event.loaded * 100 / event.total);
           $("#upprog").text(percent+"%");
              $("#upprog").width(percent+"%");
          } */
      };
      // 传输开始事件
      xhr.onloadstart = function(event) {  
          $("#upprog").text('开始上传');
      };
      // ajax过程成功完成事件
      xhr.onload = function(event) {    
         if(xhr.readyState == 4 && xhr.status == 200){    
             var b = xhr.responseText;
             if(b!='0'){
          	   $("#filepath").val(b);
          	   layer.msg("上传成功");
               $("#updiv").hide();
			             $("#msgdiv").show();			            
			              var myresponce = JSON.parse(event.currentTarget.response);
			              $("#rcount").text( myresponce[0].rcount);
			              $("#ecount").text( myresponce[0].ecount);			              
			              if("0"==myresponce[0].rcount){
			               $("#comit").hide();			              
			              }			              
			              var msg = "";
			              for(var i=0 ;i<myresponce[0].errorBean.length;i++){
			                 var sb = myresponce[0].errorBean[i]
			               	msg+=sb.account+":  "+sb.msg+"<br><br>";			              
			              }					               
					      $("#emsg").html( msg); 
             }else{
             alert("上传失败");
             }                   
     }  
      };
      // ajax过程发生错误事件
      xhr.onerror = function(event) { 
          $("#upprog").text('发生错误');
      };
      // ajax被取消
      xhr.onabort = function(event) { 
          $("#upprog").text('操作被取消');
      };
      // loadend传输结束,不管成功失败都会被触发
      xhr.onloadend = function (event) { 
      };
      // 发起ajax请求传送数据
      xhr.open('POST', 'homework_HomeworkUpload_analysisExcel', true);
      xhr.send(fd);
  }

check方法在点击上传时会进行判断,验证这个文件是否为空并且是不是你指定上传格式的文件

  function check(){
      var file = $("#myfile").val();
      if(file==""){
      layer.alert("请选择文件");
      }else if(myOnselect(file)){
         upload();
      }
  }
 	function myOnselect(file){
 	
 		var afileArray=file.split(".");
 		var last = afileArray[afileArray.length-1];
        	if(last!="xls"&&last!="XLS"){
        		  layer.alert("格式不正确!", 8);
        		return false;
        	}
		return true;
 	} 

注意:两种上传方式中myOnselect方法有一个地方不一样,自己仔细看

2.Jquery自带的上传方法

引入js文件

<script type="text/javascript" src="<%=basePath %>js/jquery.min.js"></script>
<script language="javascript" src="<%=basePath %>jsupload/swfobject.js"></script>
	<script language="javascript" src="<%=basePath %>jsupload/jquery.uploadify.v2.1.0.min.js"></script>
<Div>
 <div style="position: relative;">
  <Div  style="position: absolute;left: 0;top: 0;z-index: 0">
	<input type="button"  id="fileins"  />
 </Div>
<div style="position: absolute;left: 15;top: 0;z-index: 1000">
	<input type="file" name="fileInput"  id="fileInput" />
</div>
					   	 	
 <Div  style="position: absolute;left: 125;top: 0;">
	<button id="upload"  onclick="javascript:jQuery('#fileInput').uploadifyUpload()"></button>
	</Div>
	</div>
	</Div>
$(document).ready(function() {
				$("#upload")[0].disabled=true;	
		        $('#fileInput').uploadify({   
			 		'uploader': "<%=basePath %>jsupload/swf/uploadify.swf?random=" + (new Date()).getTime(),
			 		'wmode' : 'transparent',
                    'hideButton'  : true,
                    'buttonText':'     ',
			        'script': 'homework_HomeworkUpload_analysisExcel',   //指定服务端处理类入口
			        'folder': 'uploadFile',
			        'displayData': 'all', 
			        'cancelImg' : "images/cancel.png",  
			        'fileDataName': 'fileInput', //和input的name属性值保持一致就好,Struts2就能处理了    
			        'queueID': 'fileQueue', 
			        'auto': false,//是否选取文件后自动上传   
			        'multi': false,//是否支持多文件上传
        			'simUploadLimit' : 1,//每次最大上传文件数  
			        'sizeLimit': 10240000000, 					
			        'onSelect': function(e, queueId,fileObj) { 	            
			        	    $("#upload")[0].disabled=false;
			        	    var flag = myOnselect(fileObj);
			        	    if(!flag){
			        	     $("#upload")[0].disabled=true;
			        	     }
			        	      
			        	    return flag;
			         },
			         'onCancel':function(file){ 
			         },		         'onComplete':function(event,queueId,fileObj,response,data){  			    			           
			             $("#updiv").hide();
			             $("#msgdiv").show();			            
			              var myresponce = eval(response);			              
			              $("#rcount").text( myresponce[0].rcount);
			              $("#ecount").text( myresponce[0].ecount);			              
			              if("0"==myresponce[0].rcount){
			               $("#comit").hide();			              
			              }		              
			              var msg = "";
			              for(var i=0 ;i<myresponce[0].errorBean.length;i++){
			                 var sb = myresponce[0].errorBean[i]
			               	msg+=sb.account+":  "+sb.msg+"<br><br>";			              
			              }					               
					      $("#emsg").html( msg);         			          
			         }       
		        });   
		    });

cancel 方法在有开启多文件上传时有用到,当然这里示例是单文件上传,这个方法可以不写

  function cancel(){
	    javascript:jQuery('#fileInput').uploadifyClearQueue();
		    }

check方法在点击上传时会进行判断,验证这个文件是否为空并且是不是你指定上传格式的文件

  function check(){
      var file = $("#myfile").val();
      if(file==""){
      layer.alert("请选择文件");
      }else if(myOnselect(file)){
         upload();
      }
  }

function myOnselect(file){ 	
 		var afileArray=file.name.split(".");
 		var last = afileArray[afileArray.length-1];
        	if(last!="xls"&&last!="XLS"){
        		  layer.alert("格式不正确!", 8);
        		return false;
        	}
		return true;
 	} 

3.其它方法

现在前端框架有layer、zui、vue等,这些框架自己有封装好的方法,大家可以去官网去了解一下资料齐全

后端读取文件方法

后端接收方法都可以跟前面两种上传方法对接上

public void analysisExcel() {
		try {
			HttpServletResponse response = null;
			response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			ExcelTool excelTool = new ExcelTool();
			List<HomeworkCommentBean> studentBeans = excelTool.analysisHome(fileInput);
			//正确的数据集合
			List<HomeworkCommentBean> rightStus = new ArrayList<HomeworkCommentBean>();
			List<HomeworkCommentBean> allStus = new ArrayList<HomeworkCommentBean>();
			//错误日志集合
			List<StuCheckLogBean> stuCheckLogBeans = new ArrayList<StuCheckLogBean>();
		    //获取学生集合
			UserBean userBean = (UserBean) ActionContext.getContext()
					.getSession().get("LOGINUSER");
			String STUS = userBean.getUserId() + "STUS";
			List<HomeWorkScoreBean> stus = (List<HomeWorkScoreBean>) ActionContext.getContext().getSession().get(STUS);
			for (int i = 0; i < studentBeans.size(); i++) {
				
				HomeworkCommentBean commentBean = studentBeans.get(i);
				boolean flag = true;
				String str = "";

				/********* 学号 **********/
				if ("".equals(commentBean.getStuAccount()) ||commentBean.getStuAccount().length()==0) {
					str += "学号不能为空,";
					flag = false;

				} else if (!Pattern.matches("^[a-zA-Z]{2}[0-9A-Z]{6,8}$",
						commentBean.getStuAccount())) {
					str += "学号格式不正确,";
					flag = false;
				}else{
					for (int j = 0; j < stus.size(); j++) {
						if(stus.get(j).getStuAccount().equals(commentBean.getStuAccount())){
							flag = true;
							break;
						}else{
							flag=false;
						}
					}
					if(!flag){
						str += "该学生不是这个班级的,";
					}
				}
				
				
				/********* 评级 **********/
				if ("".equals(commentBean.getLevel()) ||commentBean.getLevel().length()==0) {
					str += "评级未填写,";
					flag = false;

				} else if (!Pattern.matches("^[a-dA-D]{1}$",
						commentBean.getLevel().trim())) {
					str += "评级格式不正确,";
					flag = false;
				}
				
				/********* 评语 **********/
				if ("".equals(commentBean.getComment()) ||commentBean.getComment().length()==0) {
					str += "评语未填写,";
					flag = false;
				} else if (commentBean.getComment().trim().length()>100) {
					str += "评语文字太长,";
					flag = false;
				}
				
				/********* 姓名 **********/
				if ("".equals(commentBean.getStuRealname()) ||commentBean.getStuRealname().length()==0) {
					str += "姓名不能为空,";
					flag = false;
				}

				/*************************/

				if (flag) {
					rightStus.add(commentBean);
				} else {
					StuCheckLogBean checkLogBean = new StuCheckLogBean();
					checkLogBean.setAccount(commentBean.getStuAccount());
					checkLogBean.setMsg(str);
					stuCheckLogBeans.add(checkLogBean);
				}
				
				allStus.add(commentBean);
			}
			//正确的结合放入Session
			/*UserBean userBean = (UserBean) ActionContext.getContext()
					.getSession().get("LOGINUSER");*/
			String  homeWorkScore = userBean.getUserId() + "_UPLOADHWMSG";
			ActionContext.getContext().getSession().put(homeWorkScore, rightStus);
			
			//excel 验证信息下发
			StuCheckRequest checkRequest = new StuCheckRequest();
			checkRequest.setRcount(rightStus.size() + "");
			checkRequest.setEcount(stuCheckLogBeans.size() + "");
			checkRequest.setErrorBean(stuCheckLogBeans);
			JSONArray jsonArray = JSONArray.fromObject(checkRequest);
			response.getWriter().print(jsonArray.toString());
			response.getWriter().flush();						
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	public List<StudentBean> analysisStu(File fileName)
			throws FileNotFoundException, IOException {
		List<StudentBean> studentsBeans = new ArrayList<StudentBean>();
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(
				fileName));
		for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
			if (hssfSheet == null) {
				continue;
			}
			/* 循环行Row */
			for (int rowNum = 2; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
				HSSFRow hssfRow = hssfSheet.getRow(rowNum);
					
				if (hssfRow == null) {
					continue;
				}

				String str = "";
				for (int i = 0; i < hssfRow.getLastCellNum(); i++) {
					if (hssfRow.getCell(i) != null) {
						str += hssfRow.getCell(i);
						
					}
				}
				if (str.length() <= 0) {
					continue;
				}

				StudentBean studentBean = new StudentBean();
				studentBean.setStuAccount(check(hssfRow.getCell(0)));
				studentBean.setStuRealname(check(hssfRow.getCell(1)));
				studentBean.setStuSex(trims(hssfRow.getCell(2)));
				studentBean.setStuSchoolNA(check(hssfRow.getCell(6)));
				studentBean.setStuSchoolMAj(check(hssfRow.getCell(7)));
				studentBean.setStuEDU(check(hssfRow.getCell(8)));
				studentBean.setStu_schoolgrad(toDate(hssfRow.getCell(9)));
				studentBean.setStutype(types(hssfRow.getCell(10)));
				studentBean.setStuTel(getStringVal(hssfRow.getCell(11)));
				studentBean.setStu_IDcardNo(hssfRow.getCell(12).toString());//身份证号
				studentsBeans.add(studentBean);
			}
		}
		return (studentsBeans);
	}```