poi之Excel上传
poi之Excel上传
@RequestMapping(value = "/import", method = RequestMethod.POST) public String importFile(MultipartFile file,RedirectAttributes redirectAttributes) { log.debug("批量导入终端数据"); /*** * 1,解析Excel 得到List<TerminalSDMTExcel> * 2,遍历,并处理list{ * 1,判断TerminalSDMTExcel是否为空 * 2,判断id是否为空 * 3,检验Excel中的数据是否合法 * 4,TerminalSDMTExcel转TerminalSDMT * 5,入库{ * 1,判断是否存在:存在则跳过 * 2,入库 * } * } * 3、提示批量导入商户结果 */ try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<TerminalSDMTExcel> list = ei.getDataList(TerminalSDMTExcel.class); TerminalSDMT Terminal = null; for (int i=0; i < list.size(); i++) { TerminalSDMTExcel entity = list.get(i); try { //是否为空,如果没有,直接跳过 if (valiBoolean(entity)){ //判断entity中各字段是否合法 Map<String,Object> maps = checkMerchantExcel(entity); boolean flags = (Boolean) maps.get("flag"); StringBuilder checkcontext = (StringBuilder) maps.get("content"); log.debug("判断输入值是否合法"); //判断输入值是否合法 if(flags){ //合法 //转换 Terminal = excelSwitchEntity(entity); //插入 Map<String,Object> map = TerminalSDMTService.save(Terminal); String flag = (String) map.get(SysConst.RESULT); /** * =0,成功 * =-1,失败 */ if("-1".equals(flag)){ //商户已存在 failureMsg.append("\n终端编号" + entity.getTermCode()+ " 已存在; "); failureNum++; }if("0".equals(flag)){ //成功 successNum++; } }else{ //不合法 failureMsg.append("\n终端编号:" + entity.getTermCode()+ ",失败原因:"+checkcontext.toString()); failureNum++; } }else{ if(Strings.isNullOrEmpty(entity.getMerchantId()) || Strings.isNullOrEmpty(entity.getTermCode())){ failureMsg.append("\n失败原因:第"+ (i+3)+"行,商户、终端编号为必填项"); failureNum++; }else{ failureMsg.append("\n终端编号:" + entity.getTermCode()+ ",失败原因:所有项均为必填项 "); failureNum++; } } } catch (Exception ex) { failureMsg.append("\n终端编号 " + entity.getTermCode() + " 导入失败:"+ ex.getMessage()); } } if (failureNum > 0) { failureMsg.insert(0, ",失败 " + failureNum + " 条终端信息,导入信息如下:"); } addMessage(redirectAttributes, "已成功导入 " + successNum + " 条终端信息"+ failureMsg); } catch (Exception e) { addMessage(redirectAttributes, "导入终端信息失败!失败信息:" + e.getMessage()); } return "redirect:"; }
注意实体映射规则