SpringMVC 下载Excel模板和导入数据
来源:互联网 发布:什么是淘宝旺旺号啊 编辑:程序博客网 时间:2024/05/01 15:52
一:模板下载功能
页面:
window.location.href="/test/downloadModel?id="+result;id是uuid生成的一个请求ID;
java:
@ResponseBody @RequestMapping(value ="/downloadModel", method = {RequestMethod.GET}) public ResponseEntity<byte[]> downloadModel(@RequestParam("id") String id,HttpServletRequest req) throws InterruptedException { RedisClient.getInstance().put("progress_"+id,0,60*60); ResponseEntity<byte[]> download = fileService.download("files/cardKind/cardKindModel.xlsx", id, req); RedisClient.getInstance().put("progress_"+id,100,60*60); return download; }
download方法@Override public ResponseEntity<byte[]> download(String path, String id, HttpServletRequest req) { downloadLogger.info("【文件下载】 download --> 执行开始,请求文件相对路径:" + path); File file = null; try {// Resource resource = new ClassPathResource(path);// file = resource.getFile();// file=new File("c:/1.xlsx"); Resource resource=new ServletContextResource(req.getServletContext(),"file/cardKindModel.xlsx"); file = resource.getFile();// } catch (IOException e) { } catch (Exception e) { downloadLogger.info("【文件下载】 download -->执行异常,无法加载到服务端文件,请求文件相对路径:" + path, e); return null; } RedisClient.getInstance().put("progress_" + id, 10, 60 * 60); String fileName = null; try { fileName = new String(file.getName().getBytes("utf-8"), "ISO-8859-1"); } catch (UnsupportedEncodingException e) { downloadLogger.info("【文件下载】 download -->执行异常,无法解析服务端文件,请求文件相对路径:" + path, e); return null; } RedisClient.getInstance().put("progress_" + id, 20, 60 * 60); HttpHeaders header = new HttpHeaders(); header.setContentDispositionFormData("attachment", fileName); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); RedisClient.getInstance().put("progress_" + id, 30, 60 * 60); byte[] res = null; try { res = FileUtils.readFileToByteArray(file); } catch (IOException e) { downloadLogger.info("【文件下载】 download -->执行异常,解析服务端文件为字节数组异常,请求文件相对路径:" + path, e); return null; } RedisClient.getInstance().put("progress_" + id, 90, 60 * 60); return new ResponseEntity<byte[]>(res, header, HttpStatus.CREATED); }
ps: 模板文件在webapp目录下,可以使用ServletContextResource获取文件
Resource resource=new ServletContextResource(req.getServletContext(),"file/cardKindModel.xlsx");file = resource.getFile();
二: 导入数据功能
页面:
jquery.form.js 需要引入这个js
$("#importExcel").ajaxSubmit({ url:"/card/uploadeCountsExcel?id="+id, type:"post", timeout: 1000*60*60, success:function(data){ $('#uploadp').hide(); // $("#excel_file").val(""); // console.log($(data).text()); var res = JSON.parse($(data).text()); if(res.code=="0"){ $.messager.alert('tip', '导入成功'); $("#excel_file").val(""); }else if (res.code=="20001"){ $("#excel_file").val(""); $.messager.confirm('确认对话框', '导入失败,是否查看详情?', function(r){ if (r){ // window.location.href="/card/importError?id="+key; //跳转到列表查询页 var iTop = (window.screen.availHeight - 30 - 750) / 2; var iLeft = (window.screen.availWidth - 10 - 1200) / 2; window.open("/card/importError?id="+key,"查看详情",'location=no,resizable=no,height=700,width=1200,innerWidth=1200,top='+iTop+',left='+iLeft); }else{ // alert("否"); //清除缓存 } }); }else{ $.messager.alert('tip', '导入失败,系统内部错误!'); } } });java
@ResponseBody @RequestMapping(value ="/uploadeCountsExcel", method = {RequestMethod.POST}) public JSONObject uploadeCountsExcel(@RequestParam(value="filename") MultipartFile file,@RequestParam(value="id") String id, HttpServletRequest req){ JSONObject res = fileService.importExcel(file, id); RedisClient.getInstance().put("progress_" + id, 100, 60 * 60); return res; }service
@Override public JSONObject importExcel(MultipartFile file, String id) { importExcelLogger.info("【导入次数】 importExcel -->执行开始。。。,请求ID=" + id); RedisClient.getInstance().put("progress_" + id, 1, 60 * 60); JSONObject res = new JSONObject(); //执行校验 String checkRes = checkFile(file); if (checkRes != null) { res.put("code", 10001); res.put("msg", checkRes); return res; } RedisClient.getInstance().put("progress_" + id, 5, 60 * 60); //扫描数据 JSONObject exeImportRes = exeImport(file.getOriginalFilename(), file); if(!"0".equals(exeImportRes.getString("code"))){ res.put("code",exeImportRes.getString("code")); res.put("msg",exeImportRes.getString("msg")); return res; } List<String[]> exeImportData = ( List<String[]>)exeImportRes.get("data"); RedisClient.getInstance().put("progress_" + id, 20, 60 * 60); //分析数据 JSONObject applyDataRes = applyData(exeImportData,id); RedisClient.getInstance().put("progress_" + id, 100, 60 * 60); return applyDataRes; } @Override public JSONArray queryImportError(String id) { Object o = RedisClient.getInstance().get(id); if(o==null){ return null; } JSONArray res= JSONArray.parseArray(o.toString()); if(res.size()<2){ return null; } res.remove(0); return res; } private String checkFile(MultipartFile file) { String msg = null; if (file == null) { msg = "上传的文件为空!"; return msg; } String fileName = file.getOriginalFilename(); if (fileName == null || fileName == "") { msg = "文件名不能为空!"; return msg; } Long size = file.getSize(); if (size == 0) { msg = "文件大小应该大于0!"; return msg; } if(size>1024 * 1024){ msg = "文件大小应该不超过1MB!"; return msg; } return msg; } private JSONObject exeImport(String name, MultipartFile file) { JSONObject res = new JSONObject(); Workbook wb = null; Sheet sheet = null; Row row = null; InputStream is = null; String extName = name.substring(name.lastIndexOf(".")); try { is = file.getInputStream(); } catch (IOException e) { importExcelLogger.error("【导入次数】 importExcel.exeImport -->无法根据提交的文件获取输入流!", e); res.put("code", "10002"); res.put("msg", "文件解析异常"); return res; } try {// if (".xls".equals(extName)) {// wb = new HSSFWorkbook(is);// } else if (".xlsx".equals(extName)) {// wb = new XSSFWorkbook(is);// } if (".xlsx".equals(extName)) { wb = new XSSFWorkbook(is); }else{ importExcelLogger.error("【导入次数】 importExcel.exeImport -->文件扩展名无效,只支持xlsx类型文件解析!"); res.put("code", "10002"); res.put("msg", "文件解析异常"); return res; } } catch (IOException e) { importExcelLogger.error("【导入次数】 importExcel.exeImport -->无法根据输入流得到Excel WorkBook!", e); res.put("code", "10002"); res.put("msg", "文件解析异常"); return res; } if(wb==null){ importExcelLogger.error("【导入次数】 importExcel.exeImport -->Excel WorkBook未被初始化!"); res.put("code", "10002"); res.put("msg", "文件解析异常"); return res; } sheet = wb.getSheetAt(0); int rows = sheet.getPhysicalNumberOfRows(); List<String[]> resList = new ArrayList<String[]>(); for(int j=0;j<rows;j++){ row = sheet.getRow(j);// int colNum = row.getPhysicalNumberOfCells(); String[] rowContent = new String[8]; for (int i = 0; i < 5; i++) { Cell cell = row.getCell(i); if("error".equals(getCellValueByCell(cell))){ importExcelLogger.error("【导入次数】 importExcel.exeImport -->存在未知的Cell类型!,RowNum="+j); res.put("code", "10002"); res.put("msg", "文件解析异常"); return res; } rowContent[i]=getCellValueByCell(cell); if(i==2 && rowContent[i]!=null && !"".equals(rowContent[i]) && rowContent[i].indexOf(".")>-1){ String[] split = rowContent[i].split("[.]"); rowContent[i]=split[0]; } } resList.add(rowContent); } res.put("code","0"); res.put("data",resList); return res; } private String getCellValueByCell(Cell cell){ String cellVal=""; if(cell==null||cell.toString().trim().equals("")){ return cellVal; }else{ switch (cell.getCellType()){ case XSSFCell.CELL_TYPE_STRING: cellVal=cell.getStringCellValue(); break; case XSSFCell.CELL_TYPE_NUMERIC: cellVal=String.valueOf(cell.getNumericCellValue()); break; case XSSFCell.CELL_TYPE_BLANK: cellVal=""; break; default: cellVal="error"; break; } return cellVal; } }分析数据是业务代码 就不上了。
阅读全文
0 0
- SpringMVC 下载Excel模板和导入数据
- java 实现的excel数据导入及导入模板下载
- asp.net下载Excel模板和导入导出Excel功能
- springmvc 利用模板 下载excel
- 下载导入数据模板
- SpringMVC+POI下载文件模板和导出Excel
- excel模板批量导入数据
- springmvc+excel多表头模板下载功能
- 导出模板和导入Excel
- springmvc实现excel数据分批导入数据库
- SpringMvc+POI处理excel表数据导入
- win32 导入excel文档模板,写入数据
- springMvc 中 Excel批量数据上传,利用POI解析数据保存入数据库 及模板文件下载
- 电子表格数据导入数据库和数据库下载数据到excel PHP代码phpexecl
- SpringMVC + JDBC + POI Excel导出与导入 +下载 资源
- poi实现根据excel模板,生成excel并导入数据
- C# 实现Excel导出 加载模板 导入数据到模板
- jsp页面的数据导入Excel中并下载Excel
- Android DataBinding原理解析
- redis主从复制
- 海思--Hi3516aIVE--基础
- Could not autowire. No beans of 'xxxx' type found的错误提示(IntelliJ Idea)
- 数据结构与算法之七(划分算法与快速排序)
- SpringMVC 下载Excel模板和导入数据
- mac下 adb :command not found问题解决
- 8皇后问题
- thinkphp5.0学习(七):数据库操作
- Vue 自定义指令
- python 空格替换
- 回文链表
- hadoop 8088端口网页无法打开的原因分析
- Java后端程序员1年工作经验总结