首页 > 其他分享 >多级动态表头导出-easyexcel

多级动态表头导出-easyexcel

时间:2024-04-11 14:22:42浏览次数:26  
标签:columnName easyexcel 多级 表头 columnField targetGrades xsfy targetValue columnParen

导出如下动态表头

 


主要的构造tabCols和tableData,

注意表头的字段,基本构造出了该格式所有的都能适配

    @GetMapping("/exportData")
    public void excelExport(TbDtTargetHealthMon tbDtTargetHealthMon, HttpServletResponse response) throws IOException {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        //响应内容格式
        response.setContentType("application/vnd.ms-excel");
        //设置文件名
//        String fileName =System.currentTimeMillis() + ".xlsx";

        try {
            //设置前端下载文件名
            String urlFileName = URLEncoder.encode(tbDtTargetHealthMon.getModuleName() + "健康度详情" + System.currentTimeMillis() , "UTF-8");
            response.setHeader("content-disposition", "attachment; filename=" + urlFileName + ".xlsx");

            //  *代表所有请求都可访问
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET");
            response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, " +
                    "If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ExcelWriter excelWriter = null;
        try {
            Map<String, Object> result = tbDtTargetHealthMonService.getTabCols(tbDtTargetHealthMon);
            List<Map<String, String>> tabCols = (List<Map<String, String>>) result.get("tabCols");
            List<List<String>> excelHead = head(tabCols);

            // 第一页数据
            List<Map<String, String>> dataOne = (List<Map<String, String>>) result.get("tableData");
            //5w数据一个sheet
            int batchSize = AutoExportConstants.SHEET_PAGE_SIZE;
            int totalSize = dataOne.size();
            int sheetCount = (int) Math.ceil((double) totalSize / batchSize);

            excelWriter = EasyExcelFactory.write(response.getOutputStream()).build();

            for (int i = 0; i < sheetCount; i++) {
                int fromIndex = i * batchSize;
                int toIndex = Math.min((i + 1) * batchSize, totalSize);
                List<Map<String, String>> currentData = dataOne.subList(fromIndex, toIndex);

                WriteSheet writeSheet = EasyExcel
                        .writerSheet("sheet" + (i + 1))
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .registerWriteHandler(horizontalCellStyleStrategy())
                        .head(excelHead)
                        .build();
                excelWriter.write(dataList(tabCols, currentData), writeSheet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            if(response.getOutputStream() != null){
                response.getOutputStream().close();
            }
        }
    }

    private List<List<String>> head(List<Map<String, String>> tabCols) {
        return tabCols.stream()
                .map(e -> Stream.of(e.get("columnParent"), e.get("columnName")).filter(Objects::nonNull).collect(Collectors.toList()))
                .collect(Collectors.toList());
    }

    private List<List<Object>> dataList(List<Map<String, String>> tabCols, List<Map<String, String>> mapList) {
        List<List<Object>> list = new ArrayList<List<Object>>();
        for (int i = 0; i < mapList.size(); i++) {
            Map row = mapList.get(i);

            List<Object> data = new ArrayList<Object>();
            for (int j = 0; j < tabCols.size(); j++) {
                String filed = tabCols.get(j).get("columnField");
                Object objVal = row.get(filed);
                String val = Objects.toString(objVal, "");
                data.add(val);
            }
            list.add(data);
        }
        return list;
    }

    private HorizontalCellStyleStrategy horizontalCellStyleStrategy() {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为红色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 14);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景绿色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteFont.setColor(IndexedColors.GREY_80_PERCENT.getIndex());

        contentWriteCellStyle.setWriteFont(contentWriteFont);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);

        contentWriteCellStyle.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        contentWriteCellStyle.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        contentWriteCellStyle.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        contentWriteCellStyle.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }
tabCols的格式
[{
	"columnField": "monthId",
	"columnName": "月份"
}, {
	"columnField": "latnName",
	"columnName": "本地网"
}, {
	"columnField": "销售费用整体效能",
	"columnName": "销售费用整体效能得分"
}, {
	"columnParent": "销售费用占收比",
	"columnField": "targetValue_xsfy_001",
	"columnName": "指标值"
}, {
	"columnParent": "销售费用占收比",
	"columnField": "targetGrades_xsfy_001",
	"columnName": "指标得分"
}, {
	"columnParent": "百元基础费拉动增量基础业务收入",
	"columnField": "targetValue_xsfy_002",
	"columnName": "指标值"
}, {
	"columnParent": "百元基础费拉动增量基础业务收入",
	"columnField": "targetGrades_xsfy_002",
	"columnName": "指标得分"
}, {
	"columnParent": "百元销售费用拉动增量主营收入",
	"columnField": "targetValue_xsfy_003",
	"columnName": "指标值"
}, {
	"columnParent": "百元销售费用拉动增量主营收入",
	"columnField": "targetGrades_xsfy_003",
	"columnName": "指标得分"
}, {
	"columnParent": "新增用户户均销售费用",
	"columnField": "targetValue_xsfy_004",
	"columnName": "指标值"
}, {
	"columnParent": "新增用户户均销售费用",
	"columnField": "targetGrades_xsfy_004",
	"columnName": "指标得分"
}, {
	"columnField": "渠道费用效能",
	"columnName": "渠道费用效能得分"
}, {
	"columnParent": "价值积分平均单价",
	"columnField": "targetValue_xsfy_008",
	"columnName": "指标值"
}, {
	"columnParent": "价值积分平均单价",
	"columnField": "targetGrades_xsfy_008",
	"columnName": "指标得分"
}, {
	"columnParent": "建店12月以上门店月均价值积分",
	"columnField": "targetValue_xsfy_009",
	"columnName": "指标值"
}, {
	"columnParent": "建店12月以上门店月均价值积分",
	"columnField": "targetGrades_xsfy_009",
	"columnName": "指标得分"
}, {
	"columnParent": "价值积分同比增长",
	"columnField": "targetValue_xsfy_010",
	"columnName": "指标值"
}, {
	"columnParent": "价值积分同比增长",
	"columnField": "targetGrades_xsfy_010",
	"columnName": "指标得分"
}, {
	"columnParent": "千分店占比",
	"columnField": "targetValue_xsfy_011",
	"columnName": "指标值"
}, {
	"columnParent": "千分店占比",
	"columnField": "targetGrades_xsfy_011",
	"columnName": "指标得分"
}, {
	"columnField": "客户服务费效能",
	"columnName": "客户服务费效能得分"
}, {
	"columnParent": "客户服务费占收比",
	"columnField": "targetValue_xsfy_012",
	"columnName": "指标值"
}, {
	"columnParent": "客户服务费占收比",
	"columnField": "targetGrades_xsfy_012",
	"columnName": "指标得分"
}, {
	"columnParent": "单位用户客户服务费",
	"columnField": "targetValue_xsfy_013",
	"columnName": "指标值"
}, {
	"columnParent": "单位用户客户服务费",
	"columnField": "targetGrades_xsfy_013",
	"columnName": "指标得分"
}, {
	"columnParent": "客户保有率",
	"columnField": "targetValue_xsfy_014",
	"columnName": "指标值"
}, {
	"columnParent": "客户保有率",
	"columnField": "targetGrades_xsfy_014",
	"columnName": "指标得分"
}, {
	"columnParent": "收入保有率",
	"columnField": "targetValue_xsfy_015",
	"columnName": "指标值"
}, {
	"columnParent": "收入保有率",
	"columnField": "targetGrades_xsfy_015",
	"columnName": "指标得分"
}]

 

tableData的格式
[{
	"targetValue_xsfy_008": "2.6900",
	"targetGrades_xsfy_012": "86.67",
	"targetValue_xsfy_009": "3542.0100",
	"targetGrades_xsfy_013": "93.33",
	"targetGrades_xsfy_010": "6.67",
	"targetGrades_xsfy_011": "86.67",
	"targetValue_xsfy_004": "227.9600",
	"targetValue_xsfy_002": "0.0000",
	"targetGrades_xsfy_014": "0.00",
	"targetValue_xsfy_003": "73.8400",
	"渠道费用效能": "58.67",
	"targetGrades_xsfy_015": "0.00",
	"monthId": "202401",
	"销售费用整体效能": "21.67",
	"targetValue_xsfy_011": "0.8081",
	"targetValue_xsfy_012": "1.64%",
	"targetValue_xsfy_010": "76.18%",
	"targetGrades_xsfy_001": "13.33",
	"targetGrades_xsfy_002": "0.00",
	"targetValue_xsfy_015": "0.00%",
	"targetGrades_xsfy_003": "0.00",
	"targetValue_xsfy_013": "0.7500",
	"客户服务费效能": "54.00",
	"targetGrades_xsfy_004": "73.33",
	"targetValue_xsfy_014": "0.00%",
	"targetGrades_xsfy_009": "40.00",
	"targetGrades_xsfy_008": "80.00",
	"targetValue_xsfy_001": "10.19%",
	"latnName": "合肥"
}]

 

标签:columnName,easyexcel,多级,表头,columnField,targetGrades,xsfy,targetValue,columnParen
From: https://www.cnblogs.com/omgliyq/p/18129046

相关文章

  • easyExcel分批导入文件
     原文地址: https://blog.csdn.net/qq_42060055/article/details/116139016 一些关于easyExcel导入文件操作需求:导入大数据量文件其中数据达到万级、十万级,错误文件进行错误单元格标红,可导出修改完继续导入由于数据量多大一次行全部读到内存中可能会导致内存溢出......
  • el-table 表头添加Tooltip render-header动态传参
    给el-table表头添加Tooltip,光标移动到表头问号区域,自动弹出tooltip提示render-header传参方式<el-table-columnprop="usedCredit"label="已占授信额度(元)"width="140"header-align="center"align=&......
  • C#实现的下拉多选框,下拉多选树,多级节点
    今天给大家上个硬货,下拉多选框,同时也是下拉多选树,支持父节点跟子节点!该控件是基于Telerik控件封装实现的,所以大家在使用的过程中需要引用Telerik.WinControls.dll、Telerik.WinControls.UI.dll,还有一些相关的类库,大家有需要的可以去网上自己找,另外我也会把一些动态库放到CSDN......
  • 多级编号
    问题:文档中多级编号混乱如何整理第一步:光标移至箭头处回车第二步:【增加缩进量】第三步:将原2.2.3后面的内容移到上一行,注意选取时不包括段落标记 后面段落需要使用上一级别则使用【减少缩进量】 ......
  • Stream流sorted的多级排序问题(巨坑)
    https://blog.csdn.net/qq_28165595/article/details/131152763 前言之前在给一个List集合中对象进行多属性排序,比如先根据对象中的A属性正序排序,若两个对象的A属性值相同,再根据对象的B属性进行正序排序。这种排序在实际开发中比较常见,但是这里面有个坑。举个例子先初始化一个......
  • easyExcel导入类
    一、基础类描述ExcelImport(导入工具类)ExcelRow(导入实体类)Consumer(函数参数)二、代码1、ExcelImportimportcom.alibaba.excel.context.AnalysisContext;importcom.alibaba.excel.event.AnalysisEventListener;importorg.itxl.common.utils.Consumer;importjava.uti......
  • easyExcel通用导出(非注解,多线程)
    1、基础类描述ExcelWriter(导出工具类)Query(通用查询)Consumer(函数参数)SpringBeanUtil(获取bean)2、代码ExcelWriterimportcn.hutool.core.collection.CollUtil;importcn.hutool.core.collection.ListUtil;importcn.hutool.core.util.PageUtil;importcn.hutool.core.u......
  • idea建多级目录出现问题,报错找不到xml文件,如何解决?
    ......
  • excel文件数据行携带表头信息为map
    privateList<Map<String,String>>readExcelForMap(InputStreaminput){List<Map<String,String>>list=newArrayList<>();EasyExcel.read(input,newAnalysisEventListener<Map<String,String>>(){......
  • 【数据处理包Pandas】多级索引的创建及使用
    目录一、元组作为一级索引(一)示例1(二)示例2二、引入多级索引(一)多级索引的创建(二)多级索引中的数学选取 首先,导入NumPy库和Pandas库。importnumpyasnpimportpandasaspd一、元组作为一级索引如果想产生如下图所示的学生成绩表:因为DataFrame的行索......