1、添加依赖
在pom.xml文件中添加如下依赖:
 <dependency>     <groupId>cn.hutool</groupId>     <artifactId>hutool-all</artifactId>     <version>5.8.5</version> </dependency>
  <dependency>     <groupId>org.apache.poi</groupId>     <artifactId>poi-ooxml</artifactId>     <version>4.1.2</version> </dependency>
 
  | 
 
2、简单配置使用
在controller中使用(ps:正常情况下应该在service层写逻辑,这里只做简单演示):
      @GetMapping("/export")     public void export(HttpServletResponse response) throws Exception{                  List<User> list = userService.list();         
                   ExcelWriter writer = ExcelUtil.getWriter(true);         
 
 
 
 
 
 
 
 
 
                   writer.write(list,true);
                   response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");         String fileName = URLEncoder.encode("用户信息", "UTF-8");         response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");
          ServletOutputStream out = response.getOutputStream();         writer.flush(out,true);         out.close();         writer.close();     }
           @PostMapping("/import")     public Boolean imp(MultipartFile file) throws Exception{         InputStream inputStream = file.getInputStream();         ExcelReader reader = ExcelUtil.getReader(inputStream);
          List<User> list = reader.readAll(User.class);
 
          System.out.println(list);                  boolean b = userService.saveBatch(list);         inputStream.close();         reader.close();         return b;     }
   | 
 
注意:在自定义表头别名哪里,如果不想在controller里写,可以再对应实体类的属性上添加@Alias(“xxx”)注解设置别名。但是使用@Alias注解后再使用BeanUtil.copyProperties(user,userDTO,true);//将查询的用户信息user复制给userDTO复制属性值时会失败,解决办法:
- 使用spring框架的BeanUtil工具类。
 
- 继续使用Hutool的BeanUtil类,然后在被赋值的类的属性上也通过@Alias注解设置对应相同的别名。
 
备注:Hutool官网
SpringBoot整合Hutool实现Excel导入导出