欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot+ EasyExcel实现Excel文件的导入导出

程序员文章站 2024-03-21 11:57:34
...

SpringBoot+ EasyExcel实现Excel文件的导入导出

##1.引入相关依赖

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.10</version>
        </dependency>

2.controller

 @GetMapping("/excel")
    public void  export(HttpServletResponse response,QueryRequest request, Certificate certificate)   {
        response.setContentType("application/vnd.ms-excel"); 
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            fileName = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            
            IPage<List<Certificate>> certificate1 = this.certificateService.findCertificate(request, certificate);
            List<List<Certificate>> records = certificate1.getRecords();//查出来的list 对象


            EasyExcel.write(response.getOutputStream(), Certificate.class).autoCloseStream(Boolean.FALSE).sheet("模板").doWrite(records);
        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            try {
                response.getWriter().println(JSON.toJSONString(map));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
            log.error("下载失败"+e);
        }
    }
```就ok了