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;
    }

做之前觉得很复杂,弄好后回顾了一下,只要明白其中的原理的话感觉还是挺容易的。

猜你喜欢

转载自blog.csdn.net/small_emotion/article/details/85005605