@RequestMapping(value = "/excel", method = RequestMethod.POST) @ResponseBody public String uploadExcel(@RequestParam("file") MultipartFile file, Model model) { try { List<People> employees = new ArrayList<>(); InputStream inputStream = file.getInputStream(); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row != null) { String name = row.getCell(0).getStringCellValue(); int age = (int) row.getCell(1).getNumericCellValue(); String sex = row.getCell(2).getStringCellValue(); People employee; int bed = (int) row.getCell(3).getNumericCellValue(); String str=Integer.toString(bed); int room_id =(int) row.getCell(4).getNumericCellValue(); if(sex.equals("女")) { employee = new People(name, age, "1", str,room_id); }else { employee = new People(name, age, "0", str,room_id); } employees.add(employee); } } model.addAttribute("employees", employees); for (People employee : employees) { peopleService.PeopleAdd1(employee); } return "result"; } catch (IOException | EncryptedDocumentException e) { e.printStackTrace(); } return "error";
时间: 2024-02-10 16:34:47 浏览: 25
这是一个使用Spring MVC框架进行Excel文件上传的Java代码。通过@RequestMapping注解指定请求路径和请求方法,@RequestParam注解获取上传的文件,@ResponseBody注解表示返回的是字符串类型的数据。在方法中,首先获取上传的Excel文件,然后通过WorkbookFactory类创建Workbook对象,获取Sheet对象,遍历Sheet中每一行数据,获取单元格数据并将其放入People对象中,最后将People对象添加到List集合中。最后,将List集合中的所有People对象添加到数据库中,并返回"result"字符串。如果发生异常,则返回"error"字符串。
相关问题
@RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public JsonResult upload(@RequestParam("file")MultipartFile file, @RequestParam("key")String key, HttpSession session){ Map<String,String> map = new HashMap<>(); try { map = FileUtil.upload(file); } catch (Exception e) { e.printStackTrace(); return JsonResult.error("上传失败"); }
这段代码是一个基于SpringMVC的文件上传接口。请求方法为POST,接收两个参数:一个是文件对象,一个是字符串类型的key值。上传成功后,返回一个JSON格式的数据对象。其中,调用了FileUtil.upload()方法来处理上传的文件,并将处理后的结果存储在一个Map对象中。如果上传失败,则返回一个错误提示信息。
@RequestMapping(value = "/uploadWxImg", method = RequestMethod.POST) public @ResponseBody Object uploadWxImg(@RequestParam("img") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException { Map<String, Object> map = new HashMap<String, Object>(); String name = file.getOriginalFilename(); String imgAbsolutePath = MyTool.SaveImg(file, MyTool.getImg(), name); map.put("code", 0); map.put("message", "上传成功"); map.put("data", name); System.out.println(map.toString()); return map; }
这段代码是一个基于SpringMVC框架的文件上传接口,使用POST方法接收MultipartFile类型的文件参数。其中@RequestParam注解用于指定上传文件的参数名。接口会将上传的文件保存到服务器指定的目录下,并返回一个包含上传结果的Map对象。具体实现可以参考MyTool类中的SaveImg方法和getImg方法。