1. 程式人生 > >java POI匯入Excel

java POI匯入Excel

在專案中要匯入天氣資料,Excel中內容如下:(資料隨便寫的)
在這裡插入圖片描述
谷歌瀏覽器中 <input type="file"/> 樣式不好看,因此改了下樣式,在點選文字框和點選瀏覽按鈕時都會彈出選擇檔案提示框。
部分樣式:

.file-box{ position:relative;width:340px;margin:20px;}
.txt{ height:22px;line-height:28px; border:1px solid #cdcdcd; width:180px;}
.btn{width:50px; color:#fff;background-color:#3598dc; border:0 none;height:22px; line-height:16px!important;cursor:pointer;}
.btn:hover{background-color:#63bfff;color:#fff;}
.hide{ display: none;}  

  <div id="slg" class="easyui-dialog" style="width:420px;height:350px;padding:10px 20px"  closed="true" buttons="#import-buttons">
        <div class="ftitle">匯入</div> 
   		 <form method="post" id="im"  enctype="multipart/form-data">
        	<input type="text" id="textfield"  name="textfield"  class="txt" readonly="readonly"/>
       		 <input type="button" class="btn" value="瀏覽..." id="viewBtn"/> 
       		 <input type="file" name="file" class="hide"  id="fileField"  accept=".xlsx,.xls" onchange="document.getElementById('textfield').value=this.files[0].name"/> 
    	</form>
 </div>
  	 
 <div id="import-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" id="iSure">確定</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#slg').dialog('close')">取消</a>
    </div> 

css

  $('#viewBtn').click(function(){
        $('#fileField').click();
    });
    
    //匯入
    $("#btnImport").click(function () {
            $('#slg').dialog('open').dialog('setTitle','匯入');
            $('#im').form('clear');
            url = path + '/weather/import?';
    });
    
    //匯入儲存
    $("#iSure").click(function(){    
              $('#im').form('submit',{
                    url: url,
                    onSubmit: function(){
                    	 return  $(this).form('validate');
                    },
                    success: function(result){
                        if (result == 'ok'){
                            $('#slg').dialog('close');      // close the dialog
                            $('#table').datagrid('reload');
                            $.messager.alert("提示","匯入成功");
                        } else {
                        	$.messager.alert("Error:",result);
                        }
                    }
            });
        });

主要是要獲得檔案的輸入流,在controller中:

 @RequestMapping(value = { "/import" }, method =RequestMethod.POST )
 @ResponseBody
    public String getDataFromExcel(HttpServletRequest request,HttpServletResponse response,String textfield) throws Exception{
    	String result="ok";  
    	MultipartHttpServletRequest multRequest = (MultipartHttpServletRequest) request;    
       MultipartFile file = multRequest.getFile("file");  //獲得上傳的excel檔案;
       if(file.isEmpty()){  
             throw new Exception("檔案不存在!");  
          }  
         InputStream in =null;  //建立輸入流;
         List<List<Object>> list = null;  
         in = file.getInputStream();  //獲得檔案輸入流
     
          String extString =  textfield.substring(textfield.lastIndexOf(".")+1);
		 Workbook workbook;
		 if (extString.equals("xlsx")) {     //.xlsx檔案用XSSFWorkbook;
			 workbook=new XSSFWorkbook(in);
		}else {
			workbook=new HSSFWorkbook(in);   // .xls檔案用HSSFWorkbook
		}
         in.close(); 
         try {
        	 Sheet sheet0=workbook.getSheetAt(0);//第一個工作表
        	 for (Row row : sheet0) {  //迴圈每一行
				if (row.getRowNum()<1) { //不拿第一行資料
					continue;
				}
				 for (int i = 0; i < 6; i++) {
					 row.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
				}
				
			     String county=row.getCell(2).getStringCellValue();
			     String date =row.getCell(3).getStringCellValue();
			     Map<String, String> queryMap = new HashMap<String, String>();
			     queryMap.put("date", date);
			     queryMap.put("county", county);
			     boolean b=this.weatherService.weatherExists(queryMap);//判斷某個區的某個時間的天氣資料是否存在
			     if (b) {     //存在時則對該資料進行更新
			    	 List<Weather> w=this.weatherService.queryWeather(queryMap);
			    	 Weather wt=w.get(0);
			    	 wt.setHigh(Integer.valueOf(row.getCell(4).getStringCellValue()));
			    	 wt.setLow(Integer.valueOf(row.getCell(5).getStringCellValue()));
			    	 this.weatherService.updateWeather(wt);
				}else{   //不存在時加入到資料庫
				   Weather weather = new Weather();	   				 	 weather.setProvinceId(Long.valueOf(row.getCell(0).getStringCellValue()));					weather.setCityId(Long.valueOf(row.getCell(1).getStringCellValue()));
				  weather.setCountyId(Long.valueOf(county));
				  weather.setDate(Integer.valueOf(date ));
		 		  weather.setHigh(Integer.valueOf(row.getCell(4).getStringCellValue()));
				  weather.setLow(Integer.valueOf(row.getCell(5).getStringCellValue()));
				  this.weatherService.addWeather(weather);
				}
			}
        	 this.logService.addSuccessLog("成功匯入:" , getSessionUser(request));
		} catch (Exception e) {
			   result = "error";
	           this.logger.error("匯入發生錯誤:" + e.getMessage());
	           this.logService.addErrorLog("匯入發生錯誤:" + e.getMessage(), getSessionUser(request));
	           e.printStackTrace();
		}
		return result;
    }

做之前覺得很複雜,弄好後回顧了一下,只要明白其中的原理的話感覺還是挺容易的。