springboot excel 视图(easyexcel)

x33g5p2x  于2021-12-28 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(753)

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

                       

                      

相关文章