首先,引入所需的jar包:
如果是maven管理项目的jar包,只需在pom.xml中加上: - <!-- https:///artifact/org.apache.poi/poi -->
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>3.14</version>
- </dependency>
- <!-- https:///artifact/org.apache.poi/poi-ooxml -->
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- <version>3.14</version>
- </dependency>
POIUtil工具类的代码: POIUtil.readExcel方法读取excel文件后,把一行中的值按先后顺序组成一个数组,所有的行作为一个集合返回。我们可以在代码中循环这个集合,把数组赋值到实体类对象中。
我在前台用form表单提交file文件,因为用的SpringMVC框架,后台用MultipartFile接收,代码如下:
- /**
- * 读取excel文件中的用户信息,保存在数据库中
- * @param excelFile
- */
- @RequestMapping("/readExcel")
- public void readExcel(@RequestParam(value = "excelFile") MultipartFile excelFile,HttpServletRequest req,HttpServletResponse resp){
- Map<String, Object> param = new HashMap<String, Object>();
- List<User> allUsers = new ArrayList<User>();
- try {
- List<String[]> userList = POIUtil.readExcel(excelFile);
- for(int i = 0;i<userList.size();i++){
- String[] users = userList.get(i);
- User user = new User();
- user.setUserName(users[0]);
- user.setPassword(users[1]);
- user.setAge(Integer.parseInt(users[2]));
- allUsers.add(user);
- }
- } catch (IOException e) {
- logger.info("读取excel文件失败", e);
- }
- param.put("allUsers", allUsers);
- this.userService.insertUsers(param);
- }
调用的service层方法就不贴代码了,下面就是往数据库插入数据了。 excel文件内容:
|