1 先導入配置文件javascript
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> </dependency>
2 編寫Chontrollerhtml
/** * 上傳excel文件 * @author SHF * @version 建立時間:2018年12月14日 上午9:28:14 * @param excelInput * @param type 1:大客戶經理 2內部人員' * @return * @throws Exception */ @RequestMapping("/uploadExcel") @ResponseBody public Object uploadExcel(@RequestParam("excelInput") MultipartFile excelInput,Integer type) throws Exception{ // 檢查文件類型 String fileName = checkFile(excelInput); if("1".equals(fileName) || "2".equals(fileName)) { return new SuccessTip("請上傳Excel格式的文件"); } Workbook workbook = null; InputStream inputStream = excelInput.getInputStream(); List<String[]> list = new ArrayList<String[]>(); try { workbook = WorkbookFactory.create(inputStream); int numberOfSheets = workbook.getNumberOfSheets(); if (numberOfSheets > 0) { Sheet sheet = workbook.getSheetAt(0); if (null != sheet) { // 得到當前sheet的開始行 int firstRowNum = sheet.getFirstRowNum(); // 得到當前sheet的結束行 int lastRowNum = sheet.getLastRowNum(); for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) { // 得到當前行 Row row = sheet.getRow(rowNum); if (row == null) { continue; } // 得到當前行的開始列 int firstCellNum = row.getFirstCellNum(); // 得到當前行的列數 int lastCellNum = row.getLastCellNum(); if(lastCellNum != 3) { //必需要有三列數據 return new SuccessTip("上傳的數據不能有爲空值!"); } String[] cells = new String[row.getLastCellNum()]; // 循環當前行 for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) { Cell cell = row.getCell(cellNum); cells[cellNum] = getCellValue(cell); } list.add(cells); } } } //插入數據 if (!list.isEmpty()) { for (String[] strs : list) { Integer userId = ShiroKit.getUser().getId(); Date date = new Date(); String name = strs[0]; String dept_userType = strs[1]; String phone = strs[2]; /*if(StringUtils.isBlank(phone)) { //throw new Exception("手機號碼不能爲空"); return new SuccessTip("手機號碼不能爲空"); }*/ ProjectInnerUser tProjectInnerUser = tProjectInnerUserService.selectOne(new EntityWrapper<ProjectInnerUser>().eq("phone", phone).eq("is_enable", 1).eq("is_deleted", 0)); if(tProjectInnerUser == null) { tProjectInnerUser = new ProjectInnerUser(); tProjectInnerUser.setName(name); tProjectInnerUser.setPhone(phone); if(type == 1) { tProjectInnerUser.setDept(dept_userType); }else { tProjectInnerUser.setUserType(dept_userType); } tProjectInnerUser.setType(type); tProjectInnerUser.setRemark("excel導入的數據"); tProjectInnerUser.setIsDeleted(0); tProjectInnerUser.setIsEnable(1); tProjectInnerUser.setCreator(userId); tProjectInnerUser.setCreated(new Date()); tProjectInnerUser.setModifier(userId); tProjectInnerUser.setModified(date); tProjectInnerUserService.insert(tProjectInnerUser); }else { tProjectInnerUser.setName(name); if(type == 1) { tProjectInnerUser.setDept(dept_userType); }else { tProjectInnerUser.setUserType(dept_userType); } tProjectInnerUser.setType(type); tProjectInnerUser.setRemark("excel導入的數據"); tProjectInnerUser.setModifier(userId); tProjectInnerUser.setModified(date); tProjectInnerUserService.updateById(tProjectInnerUser); } } } } catch (EncryptedDocumentException e1) { e1.printStackTrace(); } catch (InvalidFormatException e1) { e1.printStackTrace(); } finally { if (null != workbook) { workbook.close(); } if (null != inputStream) { inputStream.close(); } } return SUCCESS_TIP; } public static String checkFile(MultipartFile file) throws IOException { // 判斷文件是否存在 if (null == file) { //throw new GunsException(BizExceptionEnum.FILE_NOT_FOUND); return "1";//文件不存在 } // 得到文件名 String fileName = file.getOriginalFilename(); // 判斷文件是不是excel文件 if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) { //throw new GunsException(BizExceptionEnum.UPLOAD_NOT_EXCEL_ERROR); return "2";//上傳的不是excel文件 } return fileName; } /** * 根據不一樣類型獲取值 * * @param cell * @return */ public static String getCellValue(Cell cell) { String cellValue = ""; if (cell == null) { return cellValue; } // 判斷數據的類型 switch (cell.getCellTypeEnum()) { case NUMERIC: // 數字 cellValue = stringDateProcess(cell); break; case STRING: // 字符串 cellValue = String.valueOf(cell.getStringCellValue()); break; case BOOLEAN: // Boolean cellValue = String.valueOf(cell.getBooleanCellValue()); break; case FORMULA: // 公式 cellValue = String.valueOf(cell.getCellFormula()); break; case BLANK: // 空值 cellValue = ""; break; case ERROR: // 故障 cellValue = "非法字符"; break; default: cellValue = "未知類型"; break; } return cellValue; } /** * 時間格式轉換 * * @param cell * @return */ public static String stringDateProcess(Cell cell) { String result = new String(); if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式 SimpleDateFormat sdf = null; if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) { sdf = new SimpleDateFormat("HH:mm "); } else {// 日期 sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); } Date date = cell.getDateCellValue(); result = sdf.format(date); } else if (cell.getCellStyle().getDataFormat() == 58) { // 處理自定義日期格式:m月d日(經過判斷單元格的格式id解決,id的值是58) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value); result = sdf.format(date); } else { double value = cell.getNumericCellValue(); CellStyle style = cell.getCellStyle(); DecimalFormat format = new DecimalFormat(); String temp = style.getDataFormatString(); // 單元格設置成常規 if (temp.equals("General")) { format.applyPattern("#"); } result = format.format(value); } return result; }
3 頁面咱們使用Jquery的form表單上傳 jquery.form.js 地址:https://github.com/jquery-form/formjava
@layout("/common/_container.html"){ <script src="${ctxPath}/static/js/jquery.form.js"></script> <div class="ibox float-e-margins"> <div class="ibox-content"> <div class="form-horizontal"> <form id="form1" method="post" enctype="multipart/form-data"> <input type="hidden" value="${type!}" id="type" name="type" accept="xlsx"> <input type="file" class="form-control" name="excelInput" id="excelInput" > <p>長傳文件的格式:</p> <div style="font-size:16px;"> <p style="float:left;width:100px;">姓名</p> <p style="float:left;width:100px;">部門</p> <p style="float:left;width:100px;">手機號碼 </p> </div> <div class="row"> <div class="flexca"> <input type="reset" class="btn btn-warning" onClick="closePag()" value="取消"> <input type="submit" id="tj" class="btn btn-primary" value="提交" style="margin-left:65px;"> </div> </div> </form> </div> </div> </div> <script type="text/javascript"> var type = null; $(function(){ type = $("#type").val();//全局配置文件的類型 1:表示從大客戶經理頁面跳轉過來的 2:表示從內部員工頁面跳轉過來的 /** 驗證文件是否導入成功 */ var options = { target:'#form1', url:Feng.ctxPath + "/bigUser/uploadExcel", success:function(data) { if(data.code == 200){ Feng.success("上傳成功!"); }else{ Feng.error("上傳失敗!"+data.message); } closePag(); } }; $('#form1').ajaxForm(options); }); //關閉彈框 function closePag(){ if(type == 1){ parent.layer.close(window.parent.TBigUser.layerIndex); window.parent.TBigUser.table.refresh(); }else{ parent.layer.close(window.parent.InsideUser.layerIndex); window.parent.InsideUser.table.refresh(); } } //--> </script> @}
或者使用ajax的方式提交表單(這樣能夠減小兼容性)jquery
$(function(){ type = $("#type").val();//全局配置文件的類型 1:表示從大客戶經理頁面跳轉過來的 2:表示從內部員工頁面跳轉過來的 $("#tj").click(function () { var formData = new FormData($('#form1')[0]); $.ajax({ type: 'post', url: Feng.ctxPath + "/bigUser/uploadExcel", data: formData, cache: false, processData: false, contentType: false, }).success(function (data) { if(data.code == 200){ Feng.success("上傳成功!"); }else{ Feng.error("上傳失敗!"+data.message); } closePag(); }).error(function () { alert("上傳失敗"); }); }); });