java 利用poi导出默认以表格展示的excel透视表

前言:

  从前,我是一个前端程序猿,怀着对打通任(前)督(后)二(开)脉(发)的梦想转了后端,自学两礼拜java+spring全家桶,直接上项目实战。最近接到一需求:将业务数据导出一张透视表。

需求开发完成已近有一段时间了,甲方的大爷大妈,爷爷奶奶们也都用的很开心,我也很开心,于是就心想咱学了也不能白学,所以写下这篇随笔。

 先看下用easypoi+POI导出的excel效果图(easypoi用来导出sheet1数据源,poi用来sheet0透视表):

图中的excel分为两个sheet, sheet1是数据源,sheet0是根据sheet的数据生成的透视表。代码如下:

// 利用esaypoi生成excel数据,即sheet1里面的数据
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "sheet1", ExcelType.XSSF), pojoClass, list);
        Sheet sheet1 = workbook.getSheetAt(0);
        sheet1.setDefaultColumnWidth(50 * 256);
        sheet1.setDefaultRowHeight((short)(2 * 256));

        // 创建数据透视sheet
        XSSFSheet  pivotSheet = (XSSFSheet )workbook.createSheet();
        pivotSheet.setDefaultColumnWidth(50 * 256);

        // 获取数据sheet的总行数
        int num = sheet1.getLastRowNum();
        // 数据透视表数据源的起点单元格位置
        CellReference topLeft = new CellReference("A1");
        // 数据透视表数据源的终点单元格位置
        CellReference botRight = new CellReference(("M"+num));
        // 数据透视表生产的起点单元格位置
        CellReference ptStartCell = new CellReference("A1");
        AreaReference areaR = new AreaReference(topLeft, botRight);
        XSSFPivotTable pivotTable = pivotSheet.createPivotTable(areaR, ptStartCell, sheet1);
        // 添加行标签
        pivotTable.addRowLabel(4); // 部门
        pivotTable.addRowLabel(1); // 科目
        pivotTable.addRowLabel(0); // 借贷方向
        pivotTable.addRowLabel(11); // 单据编号
        pivotTable.addRowLabel(12); // 凭证编号
        pivotTable.addRowLabel(9); // 付款编码
        pivotTable.addRowLabel(10); // 付款时间
        pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "分录金额");
        // 将透视表的列以表格的样式显示 这个地方弄了好久
        int count = 13; // count为数据源的列的数量
        for (int i = 0; i < count; i++) {
            CTPivotField ctPivotField = pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(i);
            ctPivotField.setOutline(false);
        }

第一次用心写博客随笔,如写的不好请使劲喷,写的一般请轻喷,写的尚可,请给个攒!

猜你喜欢

转载自www.cnblogs.com/rush-code/p/12070995.html
今日推荐