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

springboot excel 视图(easyexcel)

程序员文章站 2022-03-15 10:13:39
...

springboot excel 视图(easyexcel)

 

应用:easyexcel使用试图下载数据,保存到excel文件中

说明:可直接使用easyexcel下载数据,保存到excel文件中

 

 

*******************

示例

 

***************

pojo 层

 

Person

@Data
public class Person {

    private Integer id;
    private String name;
    private Integer age;
}

 

***************

controller 层

 

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public ModelAndView hello(ModelAndView mv){
        mv.addObject("list",data());
        mv.setView(initView("测试数据2"));

        return mv;
    }

    @SuppressWarnings("unchecked")
    private View initView(String fileName){
        return new AbstractXlsView() {

            @Override
            protected void buildExcelDocument(Map<String, Object> map, Workbook workbook, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
                if (fileName!=null){
                    httpServletResponse.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode(fileName,StandardCharsets.UTF_8)+".xlsx");
                }

                EasyExcel.write(httpServletResponse.getOutputStream(),Person.class).sheet().doWrite((List<Person>)(map.get("list")));
            }
        };
    }

    private List<Person> data(){
        List<Person> list=new ArrayList<>();

        for (int i=0;i<5;i++){
            Person person=new Person();
            person.setId(i);
            person.setName("瓜田李下 "+i);
            person.setAge(20+i);

            list.add(person);
        }

        return list;
    }
}

 

 

*******************

使用测试

 

localhost:8080/hello

                         springboot excel 视图(easyexcel)

 

                        springboot excel 视图(easyexcel)

 

 

相关标签: easyexcel