springboot集成阿里easyExcel

**pom文件**
	 
        org.springframework.boot
        spring-boot-starter
    
    
        org.springframework.boot
        spring-boot-starter-web
    
	
        com.alibaba
        easyexcel
        2.1.4
	
	
        org.apache.poi
        poi
        3.17
    
    
        org.apache.poi
        poi-ooxml
        3.17
    
    
        cglib
        cglib
        3.1
    
    
        org.projectlombok
        lombok
        1.16.22
    

注:easyexcel使用的是org.apache.poi的版本是3.17导入其他版本会导致版本冲突,讲道理这里导入easyexcel的包就可以不用导入org.apache.poi的包了,但是我试了好多次这个org.apache.poi的包如果不导入或者版本选择错误会报错
javaBean
/**

  • 做下载时的实体类,要映射字段与列的关系
    */
    @Data
    @Builder
    public class DownloadData {
    @ExcelProperty(“字符串标题”)
    private String string;
    @ExcelProperty(“日期标题”)
    private Date date;
    @ExcelProperty(“数字标题”)
    private Double doubleData;
    }

/**

  • 做上传时接收的实体类
    */
    @Data
    public class Accounts {
    private String name;
    private String password;
    private Integer age;
    }

controller层
/**

  • @author ppshi

  • @date 2019/12/19 20:25
    */
    @Controller
    @Validated
    public class ImportController {

    /**

    • 选择好文档直接上传,前提是要创建好对应的实体类
    • @param
    • @return
    • @throws Exception
      */
      @PostMapping(value = “/upload”)
      @ResponseBody
      public String uploadExcel(MultipartFile file) {
      try {
      EasyExcel.read(file.getInputStream(), Accounts.class, new DemoDataListeners()).sheet().doRead();
      } catch (IOException e) {
      e.printStackTrace();
      }
      return “success”;
      }

    /**

    • 在html页面直接下载
    • @param response
    • @throws IOException
      */
      @GetMapping("/download")
      public void download(HttpServletResponse response) throws IOException {
      response.setContentType(“application/vnd.ms-excel”);
      response.setCharacterEncoding(“utf-8”);
      String fileName = URLEncoder.encode(“测试”, “UTF-8”);
      response.setHeader(“Content-disposition”, “attachment;filename=” + fileName + “.xlsx”);
      EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet(“模板1”).doWrite(getAllUser());
      }
      public static List getAllUser() {
      List userList = new ArrayList<>();
      for (int i = 0; i < 10; i++) {
      DownloadData user = DownloadData.builder().string(“李四” + i).date(new Date()).doubleData(new Double(i)).build();
      userList.add(user);
      }
      return userList;
      }
      }
      上传,下载html页面
上传

你可能感兴趣的:(springboot集成阿里easyExcel)