easypoi-实现动态列导出excel


程序员的公众号:源1024获取更多资料,无加密无套路!

最近整理了一波电子书籍资料,包含《Effective Java中文版 第2版》《深入JAVA虚拟机》,《重构改善既有代码设计》,《MySQL高性能-第3版》,《Java并发编程实战》等等
获取方式: 关注公众号并回复 电子书 领取,更多内容持续奉上


概括:

1、使用easypoi导出excel文件

2、行头根据用户选择,动态生成

3、根据key进行列匹配,填充对应列数据

首先导入maven依赖:

        
            cn.afterturn
            easypoi-spring-boot-starter
            4.4.0
        

示例代码:

    public void exportExcel(HttpServletResponse response) {
        /**
         * 组装数据
         */
        Map map = new HashMap<>();
        map.put("name", "帕克");
        map.put("age", "11");
        map.put("subject", "语文");
        map.put("score", "70");
        Map map1 = new HashMap<>();
        map1.put("name", "火枪");
        map1.put("age", "21");
        map1.put("subject", "数学");
        map1.put("score", "80");

        /**
         * maps 存储数据
         */
        List> maps = new ArrayList<>();
        maps.add(map);
        maps.add(map1);
        /**
         * entityList 存表头,name为列名,key为对应字段,需要跟数据key一一对应
         */
        List entityList = new ArrayList<>();
        entityList.add(new ExcelExportEntity("姓名","name",20));
        entityList.add(new ExcelExportEntity("年龄","age",20));
        entityList.add(new ExcelExportEntity("学科","subject",20));
        entityList.add(new ExcelExportEntity("成绩","score",20));
        /**
         * 生成workbook
         */
        Workbook workbook = ExcelExportUtil.exportExcel(
                new ExportParams("标题", "sheet页", ExcelType.XSSF)
                , entityList
                , maps);
        downLoadExcel("test.xlsx",response,workbook);
    }

 导出下载excel

public  void downLoadExcel(String fileName, HttpServletResponse response, Workbook                     workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
导出文件效果

easypoi-实现动态列导出excel_第1张图片

备注

详细说明请参照官方文档:Easypoi使用文档

你可能感兴趣的:(excel,easypoi)