參考:https://www.cnblogs.com/hanfeihanfei/p/7079210.html
1 @RequestMapping("/importExcel.do") 2 public void import2(String xlsPath) throws IOException, BiffException { 3 4 // 導入已存在的Excel文件,獲得只讀的工作薄對象 5 FileInputStream fis = new FileInputStream(xlsPath); 6 Workbook wk = Workbook.getWorkbook(fis); 7 // 獲取第一張Sheet表 8 Sheet sheet = wk.getSheet(0); 9 // 獲取總行數 10 int rowNum = sheet.getRows(); 11 System.out.println("插入總行數:"+rowNum); 12 // 從數據行開始迭代每一行 13 for (int i = 0; i < rowNum; i++) { 14 //先判斷插入的數據是否和數據庫的數據重復 15 if(userService.findUser(sheet.getCell(0, i).getContents())>0) { 16 continue; 17 } 18 User u = new User(); 19 // getCell(column,row),表示取得指定列指定行的單元格(Cell) 20 // getContents()獲取單元格的內容,返回字符串數據。適用於字符型數據的單元格 21 // 使用實體類封裝單元格數據 22 u.setName(sheet.getCell(0, i).getContents()); 23 u.setAge(sheet.getCell(1, i).getContents()); 24 u.setNickName(sheet.getCell(2, i).getContents()); 25 userService.saveUser(u); 26 System.out.println("成功插入:"+sheet.getCell(0, i).getContents()); 27 28 29 30 /*// 判斷單元格的類型,單元格主要類型LABEL、NUMBER、DATE 31 if (sheet.getCell(2, i).getType == CellType.NUMBER) { 32 33 // 轉化為數值型單元格 34 NumberCell numCell = (NumberCell) sheet.getCell(2, i); 35 // NumberCell的getValue()方法取得單元格的數值型數據 36 info.setRscore(numCell.getValue()); 37 38 } 39 if (sheet.getCell(3, i).getType == CellType.NUMBER) { 40 NumberCell numCell = (NumberCell) sheet.getCell(3, i); 41 info.setRscore(numCell.getValue); 42 } 43 44 if (sheet.getCell(4, i).getType == CellType.DATE) { 45 DateCell dateCell = (DateCell) sheet.getCell(4, i); 46 // DateCell的getDate()方法取得單元格的日期型數據 47 info.setDate(dateCell.getDate()); 48 }*/ 49 } 50 fis.close(); 51 wk.close(); 52 }
注解都比較詳細了
前端代碼(ie8和chrome前端獲取的路徑會出問題)
<form>
<input type="file" id="fileName" name="xlsPath" /> <input
type="button" id="btn" value="提交">
</form>
1 $("#btn").click(function() { 2 var xlsPath = document.getElementById("fileName").value; 3 /* var path=getPath(xlsPath); 4 alert(path); */ 5 $.ajax({ 6 "url" : "${pageContext.request.contextPath}/importExcel.do", 7 "type" : "GET", 8 "data" : "xlsPath=" + xlsPath, 9 "dataType" : "json", 10 "success" : function(res) { 11 if (res.state == 1) { 12 alert(message); 13 } else { 14 alert(message); 15 } 16 } 17 }); 18 });
可以直接用
