提供使用excel导入数据的功能
首先使用的是ajaxfileupload这个js
通过点击上传按钮异步触发上传功能
//上传组织结构excel importExcel:function(){ yl_bg_tools.fileupload({ //页面上点击的按钮id btn:"#org-manage-upload-organization-excel", //按钮下方隐藏的input框 type=file file:"org-manage-import-organization-file", data:{ fileType:"xls", type:"usr", id:"123456" }, url:YL.REQUEST_ROOT+"/organization/importOrgExcel", uploadStart:function(){ tips.waiting("正在导入学校组织结构信息,请稍后......"); }, success:function(){ org_manage.getOrganizationList(); tips.success("导入成功!"); }, error:function(){ tips.error("导入失败!"); } }); },
var yl_bg_tools={ fileupload:function(args){ var btn_selector=args.btn, file_selector="#"+args.file, preview_selector=""; if(args.preview){ preview_selector="#"+args.preview; } $(btn_selector).off("click."+file_selector+"").on("click."+file_selector+"",function(){ if(typeof(args.btnOnClick)=="function"){ /** * target 当前被点击的jquery对象 ,init_password 初始密码 */ if(!args.btnOnClick($(this))){ return false; }; } var data=args.data, url=args.url; if(typeof(args.data)=="object"){ //如果url中已经有了? if(/?+/.test(url)){ url += "&fileType="+data.fileType+"&type="+data.type+"&id="+data.id; }else{ url += "?fileType="+data.fileType+"&type="+data.type+"&id="+data.id; } } if(typeof(args.beforefileShow)=="function"){ args.beforefileShow(); } $(file_selector).trigger("click"); $(file_selector).change(function(){ if( $(file_selector).val() != ""){ //文件开始上传时触发的事件 if(typeof(args.uploadStart)=="function"){ args.uploadStart(); } $.ajaxFileUpload({ url:url, //需要链接到服务器地址 secureuri:false, type:'POST', fileElementId:args.file, //文件选择框的id属性 dataType: 'text', success: function(data){ if(typeof(args.success)=="function"){ args.success(data); } if(args.preview){ $(preview_selector).attr("src",$(data).text()); } }, error: function (data, status, e) { if(typeof(args.error)=="function"){ args.error(data); } } }); } }); }); }, }
然后就是在controller中接收参数进行处理
/** * * 名称:importOrgExcel <br/> * 描述:倒入组织机构excel <br/> * @param session * @param request * @param response * @param fileType :文件类型 * @param type :文件所属类型 * @param id * @return String 上传文件的路径 */ @RequestMapping(value = "importOrgExcel") @ResponseBody public String importOrgExcel(HttpServletRequest request,HttpServletResponse response,String fileType,String type,String id) { //schoolCode 学校id 怎么获取学校id已经删除,这里只写部分 //上传至web服务器 String url = FileUtils.uploadToWeb(request, response,schoolCode, "school"); url=FileUtils.getSystemPath()+url; //将文件读取到set集合中 Set<List<Object>> set=ExcelUtils.readExcelToSet(url, 0); //处理该set集合 ygxTchOrganizationService.importExcel(schoolCode, set); File file=new File(url); if(file.exists())file.delete(); return url; }
/** * 文件: 上传web服务器 * * @param id * 用户ID | 课程ID | 学校ID * @param type * 文件所属类型:(参考:Constants.TYPE) * @return 图片URL相对地址 */ public static String uploadToWeb(HttpServletRequest request, HttpServletResponse response, String id,String type) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> it = multipartRequest.getFileNames(); MultipartFile uploadFile = null; /* 获得文件 */ if (it.hasNext()) uploadFile = multipartRequest.getFile(it.next()); if (null == uploadFile) return null; String filename = uploadFile.getOriginalFilename(); /* 获得文件名 */ String suffix = filename.substring(filename.lastIndexOf(".") + 1); /* 获得文件后缀 */ filename = "temp_"+String.valueOf(System.currentTimeMillis()) + "." + suffix; /* 构建新文件名 */ String sysPath = getSystemPath(); String filePath = sysPath + getUploadPath(suffix, id, type); /* 获得文件绝对路径 */ File targetFile = new File(filePath, filename); if (!targetFile.exists()) { targetFile.mkdirs(); } try { uploadFile.transferTo(targetFile); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return filePath.replace(sysPath, "") + filename; }
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; /** * * 名称:readExcelToSet <br/> * 描述:excel读取 <br/> * @param filepath * @param sheetnum * @return */ public static Set<List<Object>> readExcelToSet(String filepath, int sheetnum) { int num = 0; if (sheetnum != 0 & sheetnum >= 0) { num = sheetnum; } File file = new File(filepath); FileInputStream fint = null; Workbook workbook = null; List<Object> list = null; Set<List<Object>> set = new HashSet<List<Object>>(); try { fint = new FileInputStream(file); workbook = WorkbookFactory.create(fint); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Sheet sheet = workbook.getSheetAt(num); int start = sheet.getFirstRowNum(); int end = sheet.getLastRowNum(); //方法1,读取下一个单元格 for (int i = start + 1; i <= end; i++) { Row rowUser = sheet.getRow(i); list = new ArrayList<Object>(); Iterator<Cell> iterUser = rowUser.iterator(); while (iterUser.hasNext()) { list.add(getStringValue(iterUser.next())); } set.add(list); } //方法2,读取第N个单元格,需要提前传入一个一共有多少列这个参数column //此方法比方法1要好,比如存在单元格无值时 //方法1会采用下一个单元格的值代替此单元格,造成数据错乱 /* for (int i = start + 1; i <= end; i++) { Row rowUser = sheet.getRow(i); if(rowUser!=null){ list = new ArrayList<Object>(); int k=0; while(k<column){ try { list.add(getStringValue(rowUser.getCell(k))); } catch (Exception e) { list.add(""); } k++; } if(list.size() > 0) { set.add(list); } } }*/ return set; }
最终处理这个集合,在数据库中形成映射
/** * * 名称:importExcel <br/> * 描述:倒入组织机构excel数据 <br/> * * @param schoolCode * :学校编码 * @param set * :导入数据 * @return int 执行结果 0:失败,1:成功 * @see com.OrganizationManageService.ygx.cms.service.YgxTchOrganizationService#importExcel(java.lang.String, * java.util.Set) */ @Override public int importExcel(String schoolCode, Set<List<Object>> set) { // 新接到学院 Set<String> departmentNameSet = new HashSet<String>(); // 新接到专业 Set<String> majorNameSet = new HashSet<String>(); // 新接到班级 Set<String> clsNameSet = new HashSet<String>(); log.error(set.toString()); for (List<Object> list : set) { if (list.size() >= 1) departmentNameSet.add(String.valueOf(list.get(0))); if (list.size() >= 2 && !StringUtils.isEmpty(String.valueOf(list.get(1)))) majorNameSet.add(String.valueOf(list.get(0)) + "YUY" + String.valueOf(list.get(1))); if (list.size() >= 3 && !StringUtils.isEmpty(String.valueOf(list.get(1))) && !StringUtils.isEmpty(String.valueOf(list.get(2)))) { clsNameSet.add(String.valueOf(list.get(0)) + "YUY" + String.valueOf(list.get(1)) + "YUY" + String.valueOf(list.get(2))); } } // 获取旧的组织机构 List<Map<String, Object>> oldOrgList = getOrganization(schoolCode); // 旧的学院 Set<String> oldDepartmentNameSet = new HashSet<String>(); // 旧到专业 Set<String> oldMajorNameSet = new HashSet<String>(); // 旧的班级 Set<String> oldClsNameSet = new HashSet<String>(); for (int i = 0; oldOrgList != null & i < oldOrgList.size(); i++) { if (oldOrgList.get(i).get("dpm_code") != null) oldDepartmentNameSet.add(String.valueOf(oldOrgList.get(i).get( "dpm_name"))); if (oldOrgList.get(i).get("maj_code") != null) oldMajorNameSet.add(String.valueOf(oldOrgList.get(i).get( "dpm_name")) + "YUY" + String.valueOf(oldOrgList.get(i).get("maj_name"))); if (oldOrgList.get(i).get("cls_id") != null) oldClsNameSet.add(String.valueOf(oldOrgList.get(i).get( "dpm_name")) + "YUY" + String.valueOf(oldOrgList.get(i).get("maj_name")) + "YUY" + String.valueOf(oldOrgList.get(i).get("cls_name"))); } //有了这三个集合,后面的自己想吧 }