1. 程式人生 > >jquery.from.js 上傳excel用法小結

jquery.from.js 上傳excel用法小結

客戶端程式碼:
<form id="form1" action="http://localhost:8080/gciwebservice/import/exceltest" method="post" enctype="multipart/form-data">  
   		 					<table width="100%">
    							<tr>
									
									<td>
   		 								請選擇匯入的檔案:<input style="width: 400px" id="fileUrl" name='file' type="file"/>
   		 							</td>
   		 							<td></td>
   		 							<td> 
    									<a class="button orange icon check" style="width: 100px;" href="javascript:upload.saveImport()">匯入</a> 
    								</td>
    								
    								<!-- 測試匯出 -->
    								<td> 
    									<a class="button orange icon check" style="widt

h: 100px;" href="javascript:form1()">匯出</a> </td> </tr> </table> </form>

js程式碼:

upload.saveImport = function(){
	var xcl = $("#fileUrl").val();
//	var xcl ="C:\fakepath\問題描述.docx";
	var strs = new Array();
	if(!xcl){
		return;
	}
	custom.showMask();
	strs = xcl.split(".");
	var suffix = strs[strs.length - 1];
	if(suffix!="xls"&&suffix!="xlsx"){
		var result = new Object();
    	result.msgcode = "0";
    	result.remsg = "檔案格式不正確";
    	showMsg(result);
        custom.hideMask();
        return;
	}
	var form = $("#form1"); 
    var options  = {    
        url:'http://'+ localStorage.IPAddress + ':8080/gciwebservice/import/exceltest',    
        type:'post',    
        success:function(data){
        	var result = new Object();
        	result.msgcode = "1";
        	result.remsg = "匯入成功";
        	showMsg(result);
            custom.hideMask();
        },
        error:function(data){
        	var result = new Object();
        	result.msgcode = "0";
        	result.remsg = "匯入失敗";
        	showMsg(result);
        	custom.hideMask();
        }
    };    
    form.ajaxSubmit(options);  
};

後臺用java的servelet接收,程式碼如下:

 private static final long serialVersionUID = 1L;  
	 private Logger logger = Logger.getLogger(uploadServlet.class);
	 
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException { request.setCharacterEncoding("utf-8");  
	        response.setCharacterEncoding("utf-8");  
	        //1、建立一個DiskFileItemFactory工廠  
	        DiskFileItemFactory factory = new DiskFileItemFactory();  
	        //2、建立一個檔案上傳解析器  
	        ServletFileUpload upload = new ServletFileUpload(factory);  
	        //解決上傳檔名的中文亂碼  
	        upload.setHeaderEncoding("UTF-8");   
	        factory.setSizeThreshold(1024 * 500);//設定記憶體的臨界值為500K  
//	        File linshi = new File("E:\\linshi");//當超過500K的時候,存到一個臨時資料夾中 
	      /*  File linshi = new File("/usr/linshi");
	        factory.setRepository(linshi); */ 
	        upload.setSizeMax(1024 * 1024 * 5);//設定上傳的檔案總的大小不能超過5M  
	        try {  
	            // 1. 得到 FileItem 的集合 items  
	            List<FileItem> /* FileItem */items = upload.parseRequest(request);  
	            // 2. 遍歷 items:  
	            for (FileItem item : items) {  
	                // 若是一個一般的表單域, 列印資訊  
	                if (item.isFormField()) {  
	                    String name = item.getFieldName();  
	                    String value = item.getString("utf-8");  
	                    logger.info(name + ": " + value);
	                }  
	                // 若是檔案域則把檔案儲存到 e:\\files 目錄下.  
	                else {  
	                    String fileName = item.getName();  
	                    long sizeInBytes = item.getSize();  
	  
	                    InputStream inRead = item.getInputStream();
	                    InputStream inWrite = item.getInputStream();
	                    
	                    Map<String ,List> map = readExcel(inRead);
	                    inRead.close();
	                    
	                    List<TrainSchedulPo> tsplist = map.get("trainSchedul");
	                    
	                    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); 
	                    CompareUtil compareUtil = (CompareUtil) ctx.getBean("compareUtil");
	        		    
	                    if(tsplist!=null){
	                    	compareUtil.compareTrainSchedule(tsplist);
	                    }

	                    byte[] buffer = new byte[1024];  
	                    int len = 0;  
	                    String rooturl = request.getServletContext().getRealPath("/");
//	                    fileName = rooturl+"WEB-INF/upload/" + Utils.getNow() +fileName;//檔案最終上傳的位置 
	                    fileName = "E:\\files\\"+ Utils.getToday() +fileName;//檔案最終上傳的位置 
//	                    fileName = "/usr/"+ Utils.getToday() +fileName;//檔案最終上傳的位置 
	                    System.out.println(fileName);  
	                    logger.info("上傳檔名稱為:"+fileName);
	                    OutputStream out = new FileOutputStream(fileName);  
	  
	                    while ((len = inWrite.read(buffer)) != -1) {  
	                        out.write(buffer, 0, len);  
	                    }  
	                    out.close();  
	                    inWrite.close();  
	                }  
	            }  
	  
	        } catch (FileUploadException e) {  
	            e.printStackTrace();  
	            logger.error(e,e);
	        }  
	  
	    }
private Map<String,List> readExcel(InputStream in) {
// TODO Auto-generated method stub
Map<String,List> map = new HashMap<String,List>();
List<TrainSchedulPo> trainSchedulList = new ArrayList<TrainSchedulPo>();

List<TrafficPlanInfoPo> trafficPlanInfoList = new ArrayList<TrafficPlanInfoPo>();
Workbook rwb = null;
try {
rwb = Workbook.getWorkbook(in);
//獲取檔案的指定工作表 預設的第一個列車時刻表
//列車時刻表
Sheet sheet = rwb.getSheet(0);
//客運計劃表
//Sheet sheet2 = rwb.getSheet(1);
//行數(表頭的目錄不需要,從1開始)
    for(int i=1; i<sheet.getRows(); i++){
       if(sheet.getCell(0,i).getContents()==null||"".equals(sheet.getCell(0,i).getContents())){
       break;
       }
       TrainSchedulPo tsp = new TrainSchedulPo();
    tsp.setId(Integer.parseInt(sheet.getCell(0,i).getContents()));//id
    tsp.setTrainName(sheet.getCell(1,i).getContents());//trainName
    tsp.setArriTrainName(sheet.getCell(2,i).getContents());//arriTrainName
    tsp.setDepaTrainName(sheet.getCell(3,i).getContents());//depaTrainName
    tsp.setDepaStation(sheet.getCell(4,i).getContents());//depaStation
    tsp.setArriStation(sheet.getCell(5,i).getContents());//arriStation
    tsp.setDepaStationName(sheet.getCell(6,i).getContents());
    tsp.setArriStationName(sheet.getCell(7,i).getContents());
    tsp.setMapArriTime(sheet.getCell(8,i).getContents());
    tsp.setMapDepaTime(sheet.getCell(9,i).getContents());
    if(sheet.getCell(10,i).getContents()!=null&&!"".equals(sheet.getCell(10,i).getContents())){
    tsp.setRunType(Integer.parseInt(sheet.getCell(10,i).getContents()));
    }
    tsp.setValiStartTime(sheet.getCell(11,i).getContents());
    tsp.setValiEndTime(sheet.getCell(12,i).getContents());
    if(sheet.getCell(13,i).getContents()!=null&&!"".equals(sheet.getCell(13,i).getContents())){
    tsp.setRunCycle(Integer.parseInt(sheet.getCell(13,i).getContents()));
    }
    if(sheet.getCell(14,i).getContents()!=null&&!"".equals(sheet.getCell(14,i).getContents())){
    tsp.setRunRule(Integer.parseInt(sheet.getCell(14,i).getContents()));
    }
    if(sheet.getCell(15,i).getContents()!=null&&!"".equals(sheet.getCell(15,i).getContents())){
    tsp.setPriority(Integer.parseInt(sheet.getCell(15,i).getContents()));
    }
    tsp.setTrainType(sheet.getCell(16,i).getContents());
    if(sheet.getCell(17,i).getContents()!=null&&!"".equals(sheet.getCell(17,i).getContents())){
    tsp.setMarshalling(Integer.parseInt(sheet.getCell(17,i).getContents()));
    }
    if(sheet.getCell(18,i).getContents()!=null&&!"".equals(sheet.getCell(18,i).getContents())){
    tsp.setAscOrDesc(Integer.parseInt(sheet.getCell(18,i).getContents()));
    }
    tsp.setTrack(sheet.getCell(19,i).getContents());
    tsp.setPlatform(sheet.getCell(20,i).getContents());
    tsp.setWaitingArea(sheet.getCell(21,i).getContents());
    tsp.setCheckPort(sheet.getCell(22,i).getContents());
    tsp.setOutCheckPort(sheet.getCell(23,i).getContents());
    tsp.setCheckTime(sheet.getCell(24,i).getContents());
    if(sheet.getCell(25,i).getContents()!=null&&!"".equals(sheet.getCell(25,i).getContents())){
    tsp.setCheckTimeBenc(Integer.parseInt(sheet.getCell(25,i).getContents()));
    }
    if(sheet.getCell(26,i).getContents()!=null&&!"".equals(sheet.getCell(26,i).getContents())){
    tsp.setCheckRelaMinute(Integer.parseInt(sheet.getCell(26,i).getContents()));
    }
    tsp.setStopCheckTime(sheet.getCell(27,i).getContents());
    if(sheet.getCell(28,i).getContents()!=null&&!"".equals(sheet.getCell(28,i).getContents())){
    tsp.setStopCheckTimeBenc(Integer.parseInt(sheet.getCell(28,i).getContents()));
    }
    if(sheet.getCell(29,i).getContents()!=null&&!"".equals(sheet.getCell(29,i).getContents())){
    tsp.setStopCheckRelaMinute(Integer.parseInt(sheet.getCell(29,i).getContents()));
    }
    if(sheet.getCell(30,i).getContents()!=null&&!"".equals(sheet.getCell(30,i).getContents())){
    tsp.setChanTrainNameFlag(Integer.parseInt(sheet.getCell(30,i).getContents()));
    }
    if(sheet.getCell(31,i).getContents()!=null&&!"".equals(sheet.getCell(31,i).getContents())){
    tsp.setArriRelaDay(Integer.parseInt(sheet.getCell(31,i).getContents()));
    }
    if(sheet.getCell(32,i).getContents()!=null&&!"".equals(sheet.getCell(32,i).getContents())){
    tsp.setDepaRelaDay(Integer.parseInt(sheet.getCell(32,i).getContents()));
    }
    tsp.setOutCheckTime(sheet.getCell(33,i).getContents());
    if(sheet.getCell(34,i).getContents()!=null&&!"".equals(sheet.getCell(34,i).getContents())){
    tsp.setOutCheckTimeBenc(Integer.parseInt(sheet.getCell(34,i).getContents()));
    }
    if(sheet.getCell(35,i).getContents()!=null&&!"".equals(sheet.getCell(35,i).getContents())){
    tsp.setOutCheckRelaMinute(Integer.parseInt(sheet.getCell(35,i).getContents()));
    }
    tsp.setOutStopCheckTime(sheet.getCell(36,i).getContents());
    if(sheet.getCell(37,i).getContents()!=null&&!"".equals(sheet.getCell(37,i).getContents())){
    tsp.setOutStopCheckTimeBenc(Integer.parseInt(sheet.getCell(37,i).getContents()));
    }
    if(sheet.getCell(38,i).getContents()!=null&&!"".equals(sheet.getCell(38,i).getContents())){
    tsp.setOutStopCheckRelaMinute(Integer.parseInt(sheet.getCell(38,i).getContents()));
    }
    if(sheet.getCell(39,i).getContents()!=null&&!"".equals(sheet.getCell(39,i).getContents())){
    tsp.setStopFlag(Integer.parseInt(sheet.getCell(39,i).getContents()));
    }
    tsp.setStopStartTime(sheet.getCell(40,i).getContents());
    tsp.setStopEndTime(sheet.getCell(41,i).getContents());
    if(sheet.getCell(42,i).getContents()!=null&&!"".equals(sheet.getCell(42,i).getContents())){
    tsp.setConfCompFlag(Integer.parseInt(sheet.getCell(42,i).getContents()));
    }
        //把剛獲取的列存入list
    trainSchedulList.add(tsp);
    }
//            ApplicationContext act = ContextLoader.getCurrentWebApplicationContext();
            map.put("trainSchedul", trainSchedulList);
            
            /*for(int i=1; i<sheet2.getRows(); i++){
              if(sheet2.getCell(0,i).getContents()==null||"".equals(sheet2.getCell(0,i).getContents())){
       break;
       }
            TrafficPlanInfoPo tpip = new TrafficPlanInfoPo();
            tpip.setId(Integer.parseInt(sheet2.getCell(0,i).getContents()));//id
            tpip.setPlanDate(sheet2.getCell(1,i).getContents());//planDate
            if(sheet2.getCell(2,i).getContents()!=null&&!"".equals(sheet2.getCell(2,i).getContents())){
            tpip.setTrainID(Integer.parseInt(sheet2.getCell(2,i).getContents()));//trainID
            }
            tpip.setTrainName(sheet2.getCell(3,i).getContents());//trainName
            tpip.setArriTrainName(sheet2.getCell(4,i).getContents());//arriTrainName
            tpip.setDepaTrainName(sheet2.getCell(5,i).getContents());//depaTrainName
            tpip.setDepaStation(sheet2.getCell(6,i).getContents());//depaStation
            tpip.setArriStation(sheet2.getCell(7,i).getContents());//arriStation
            tpip.setDepaStationName(sheet2.getCell(8,i).getContents());//depaStationName
            tpip.setArriStationName(sheet2.getCell(9,i).getContents());//arriStationName
            tpip.setMapArriTime(sheet2.getCell(10,i).getContents());//mapArriTime
            tpip.setArriTime(sheet2.getCell(11,i).getContents());//arriTime
            if(sheet2.getCell(12,i).getContents()!=null&&!"".equals(sheet2.getCell(12,i).getContents())){
            tpip.setArriStatus(Integer.parseInt(sheet2.getCell(12,i).getContents()));//arriStatus
            }
            if(sheet2.getCell(13,i).getContents()!=null&&!"".equals(sheet2.getCell(13,i).getContents())){
            tpip.setArriLateMinute(Integer.parseInt(sheet2.getCell(13,i).getContents()));//arriLateMinute
            }
            tpip.setArriLateReason(sheet2.getCell(14,i).getContents());//arriLateReason
    tpip.setMapDepaTime(sheet2.getCell(15,i).getContents());//mapDepaTime
    tpip.setDepaTime(sheet2.getCell(16,i).getContents());//depaTime
    if(sheet2.getCell(17,i).getContents()!=null&&!"".equals(sheet2.getCell(17,i).getContents())){
    tpip.setDepaStatus(Integer.parseInt(sheet2.getCell(17,i).getContents()));//depaStatus
    }
    if(sheet2.getCell(18,i).getContents()!=null&&!"".equals(sheet2.getCell(18,i).getContents())){
    tpip.setDepaLateMinute(Integer.parseInt(sheet2.getCell(18,i).getContents()));//depaLateMinute
    }
    tpip.setDepaLateReason(sheet2.getCell(19,i).getContents());//depaLateReason
    tpip.setMapCheckTime(sheet2.getCell(20,i).getContents());//mapCheckTime
    tpip.setCheckTime(sheet2.getCell(21,i).getContents());//checkTime
    tpip.setMapStopCheckTime(sheet2.getCell(22,i).getContents());//mapStopCheckTime
    tpip.setStopCheckTime(sheet2.getCell(23,i).getContents());//stopCheckTime
    tpip.setMapOutCheckTime(sheet2.getCell(24,i).getContents());//mapOutCheckTime
    tpip.setOutCheckTime(sheet2.getCell(25,i).getContents());//outCheckTime
    tpip.setMapStopOutCheckTime(sheet2.getCell(26,i).getContents());//mapStopOutCheckTime
    tpip.setStopOutCheckTime(sheet2.getCell(27,i).getContents());//stopOutCheckTime
    tpip.setMapTrack(sheet2.getCell(28,i).getContents());//mapTrack
    tpip.setTrack(sheet2.getCell(29,i).getContents());//track
    tpip.setMapPlatform(sheet2.getCell(30,i).getContents());//mapPlatform
    tpip.setPlatform(sheet2.getCell(31,i).getContents());//platform
    tpip.setMapWaitingArea(sheet2.getCell(32,i).getContents());//mapWaitingArea
    tpip.setWaitingArea(sheet2.getCell(33,i).getContents());//waitingArea
    tpip.setMapCheckPort(sheet2.getCell(34,i).getContents());//mapCheckPort
    tpip.setCheckPort(sheet2.getCell(35,i).getContents());//checkPort
    tpip.setMapOutCheckPort(sheet2.getCell(36,i).getContents());//mapOutCheckPort
    tpip.setOutCheckPort(sheet2.getCell(37,i).getContents());//outCheckPort
    tpip.setMapMarshalling(sheet2.getCell(38,i).getContents());//mapMarshalling
    if(sheet2.getCell(39,i).getContents()!=null&&!"".equals(sheet2.getCell(39,i).getContents())){
    tpip.setMarshalling(Integer.parseInt(sheet2.getCell(39,i).getContents()));//marshalling
    }
    if(sheet2.getCell(40,i).getContents()!=null&&!"".equals(sheet2.getCell(40,i).getContents())){
    tpip.setMapAscOrDesc(Integer.parseInt(sheet2.getCell(40,i).getContents()));//mapAscOrDesc
    }
    if(sheet2.getCell(41,i).getContents()!=null&&!"".equals(sheet2.getCell(41,i).getContents())){
    tpip.setAscOrDesc(Integer.parseInt(sheet2.getCell(41,i).getContents()));//ascOrDesc
    }
    if(sheet2.getCell(42,i).getContents()!=null&&!"".equals(sheet2.getCell(42,i).getContents())){
    tpip.setStopFlag(Integer.parseInt(sheet2.getCell(42,i).getContents()));//stopFlag
    }
    tpip.setModiFlag(Integer.parseInt(sheet2.getCell(42,i).getContents()));//modiFlag
            
    tpip.setModiTime(sheet2.getCell(43,i).getContents());//modiTime
    tpip.setBroaPlanCreaTime(sheet2.getCell(44,i).getContents());//broaPlanCreaTime
    tpip.setDeleFlag(Integer.parseInt(sheet2.getCell(46,i).getContents()));//deleFlag
    tpip.setLateChanTime(sheet2.getCell(47,i).getContents());//lateChanTime
    tpip.setUndeLateChanTime(sheet2.getCell(48,i).getContents());//undeLateChanTime
    tpip.setCheckPortChanTime(sheet2.getCell(49,i).getContents());//checkPortChanTime
    tpip.setWaitingAreaChanTime(sheet2.getCell(50,i).getContents());//waitingAreaChanTime
    tpip.setOutCheckPortChanTime(sheet2.getCell(51,i).getContents());//outCheckPortChanTime
    tpip.setTrackChanTime(sheet2.getCell(52,i).getContents());//trackChanTime
    tpip.setPlatformChanTime(sheet2.getCell(53,i).getContents());//platformChanTime
    tpip.setArriLateChanTime(sheet2.getCell(54,i).getContents());//arriLateChanTime
    tpip.setArriUndeLateChanTime(sheet2.getCell(55,i).getContents());//arriUndeLateChanTime
    trafficPlanInfoList.add(tpip);
            }*/
//    map.put("trafficPlanInfo", trafficPlanInfoList);
    return map;
           
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e,e);
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e,e);
return null;
}
}  

其中客戶端部分name屬性必須填寫,否則後臺接收不到資料