1. 程式人生 > >java導入Excel

java導入Excel

java orm ets ebo users ring workbook 空串 emp

前臺:

 1   <form id = "import_form">
 2         <input id="import_file_name" name="" value="" type="text"/>
 3         <input id="import_file" onchange="showFileName()" name="file" value="" type="file"/>
 4         <input type="button" id = "import_box_sure" value="確定"/>
 5     </form>
 6
7 <script> 8 function showFileName(){ 9 $("#import_file_name").val($("#import_file").val()); 10 } 11 12 $(function(){ 13 14 $(‘#import_box_sure‘).live(‘click‘, function() { 15 if(!$("import_file").val()){
16 alert("請導入文件"); 17 return; 18 } 19 }); 20 21 $("#import_form").ajaxSubmit({ 22 type:‘post‘, 23 url:"./importUsers", 24 success:function(data){ 25 if
(data && data.code=="200"){ 26 alert("導入成功"); 27 //彈窗隱藏 28 } 29 } 30 }); 31 32 } 33 34 </script>

後臺:

 1 @RequestMapping(value="/importUsers",method = RequestMethod.POST)
 2     @ResponseBody
 3     public Object importUsers(@RequestParam MultipartFile file){
 4         excelToUserList(is);
 5     }
 6     
 7     public static  List<User> excelToUserList(InputStream is){
 8         final ArrayList<User> resultList = new ArrayList<User>();
 9         XSSFWorkbook wb = new XSSWorkbook(is);
10         
11         XSSFSheet sheet = wb.getSheetAt(0);
12          
13         for(int currentRowNum=0;currentRowNum<sheet.getLastRowNum();currentRowNum++){
14             XSSFRow row = sheet.getRow(currentRowNum);
15             
16             if(null==row){
17                 //遇到真正空行就退出
18                 break;
19             }
20             //第一行是標題,第二行是表頭,從第三行開始才是數據
21             if(currentRowNum<2){
22                 continue;
23             }
24             
25             Map<String,Object> resp = rowIsEmpty(row);
26             int code = (int)resp.get("code");
27             //等於1說明當前行中沒有有效數據,也認為是空行
28             if (code==1) {
29                 break;
30             }
31             
32             //這裏才開始真正遍歷每行的單元格數據todo,方法參考 rowIsEmpty方法
33             
34         }
35             
36         
37         
38     }
39     
40     
41     
42     
43     //判斷當前行中是否有有效數據。當前行中每一個單元格中都沒有有效數據(如空串""),則認為當前行沒有數據
44     private static Map<String,Object> rowIsEmpty(XSSFRow row){
45         HashMap<String, Object> map = new HashMap<String,Object>();
46         int cellNum = row.getLastCellNum();
47         for(int j=0;j<cellNum;j++){
48             XSSCell cell = row.getCell(j);
49             if(cell==null || "".equals(cell.getStringCellValue())){
50                 continue;
51             }else{
52                 //只要有一個單元格不滿足,則此行不為空
53                 map.put("code", 0);
54                 return map;
55             }
56         }
57         //當前行全部單元格都沒有有效數據
58         map.put("code", 1);
59         return map;
60     }
61 }

java導入Excel