2015-08-28 129 views
0

我试图使用Apache-POI在Excel中使用从数据库中检索的数据创建数据透视表。 目前我可以在数据透视表上创建正常的列标签,但是我希望能够添加父列表。使用Apache POI将父列添加到Excel数据透视表

这是我多么希望我的表看: enter image description here

这是我正在创建的数据透视表:

XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference(
    fromSheet.getSheetName() + "!" + tableRange), 
    new CellReference("A6")); 

pivotTable.addRowLabel(0); // the row label 

pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2, "Child Column 1"); 
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3, "Child Column 2"); 

我如何添加一个包含两个子列的父列?

回答

2

您应该在“列标签”而不是“值”中添加父列。

但是POI API没有提供addColumn功能,请尝试以下功能父列添加到列标签

public static void addColumLabels(XSSFPivotTable pivotTable, int columnIndex) { 
    AreaReference pivotArea = getPivotArea(pivotTable); 
    int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol(); 

    if (columnIndex > lastColIndex && columnIndex < 0) { 
     throw new IndexOutOfBoundsException(); 
    } 

    CTPivotFields pivotFields = pivotTable.getCTPivotTableDefinition().getPivotFields(); 

    CTPivotField pivotField = CTPivotField.Factory.newInstance(); 
    CTItems items = pivotField.addNewItems(); 

    pivotField.setAxis(STAxis.AXIS_COL); 
    pivotField.setShowAll(false); 
    for (int i = 0; i <= lastColIndex; i++) { 
     items.addNewItem().setT(STItemType.DEFAULT); 
    } 
    items.setCount(items.sizeOfItemArray()); 
    pivotFields.setPivotFieldArray(columnIndex, pivotField); 

    // colfield should be added for the second one. 
    CTColFields colFields; 
    if (pivotTable.getCTPivotTableDefinition().getColFields() != null) { 
     colFields = pivotTable.getCTPivotTableDefinition().getColFields(); 
    } else { 
     colFields = pivotTable.getCTPivotTableDefinition().addNewColFields(); 
    } 
    colFields.addNewField().setX(columnIndex); 
    colFields.setCount(colFields.sizeOfFieldArray()); 
} 
相关问题