excle导入 文件file上传ajxa请求
/** * 导入Excel文件保存数据 */ @RequestMapping("/upload") @ResponseBody public JSONObject upload(@RequestBody MultipartFile file, HttpServletRequest request, HttpServletResponse response) { JSONObject result = new JSONObject(); String path = request.getSession().getServletContext() .getRealPath("upload") + DateFormatUtils.format(new Date(), "/yyyy/MM/dd"); int okCount = 0; int failCount = 0; try { String fileName = file.getOriginalFilename(); String filetype=fileName.substring(fileName.lastIndexOf("."),fileName.length()); if(StringUtils.isBlank(filetype) || (!filetype.equals(".xls") && !filetype.equals(".xlsx"))){ result.put("code", 0); result.put("message", "文件类型错误,需要xls或xlsx类型文件!"); HtmlUtil.writerJson(response, result); return result; } // 文件名以当前时间戳替换,防止重名 fileName = Long.toString(System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf(".")) .toLowerCase(); File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } file.transferTo(targetFile); ExcelUtil eu = new ExcelUtil(); // 从第一行开始读取 eu.setStartReadPos(1); String src_xlspath = path+"http://www.mamicode.com/"+fileName; //String dist_xlsPath = "D:\\1.xls"; List<Object> rowList; rowList = eu.readExcel(src_xlspath); if(rowList!=null && rowList.size()>0){ for(int i=0; i<rowList.size();i++){ ArrayList strList = (ArrayList) rowList.get(i); ExIndustryEntity exIndustryEntity = new ExIndustryEntity(); for(int j=0; j<5;j++){ String str = (String) strList.get(j); switch (j) { case 0: exIndustryEntity.setName(str); break; case 1: exIndustryEntity.setArea(str); break; case 2: exIndustryEntity.setYield(str); break; case 3: exIndustryEntity.setValue(str); break; default: exIndustryEntity.setYear(str); break; } } JSONObject json = exIndustryService.savaExIndustry(exIndustryEntity); if("0".equals(json.getString("code"))){ okCount++; }else { failCount++; } } } result.put("code",0); result.put("msg","导入成功 "+okCount+" 条,失败 "+failCount+" 条"); } catch (Exception e) { result.put("code", 0); result.put("message", "excel导入失败!"); e.printStackTrace(); } return result; }
,温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/40444.html