4
votes

How can I add Colum Label using Apache POI 3.12.

Name Team Country Player Status

a   fcb z   active

b   rm  z   injured

c   fcb z   active

d   rm  z   injured

e   am  z   banned

f   rcb z   banned

g   rm  y   injured

h   am  y   active

i   am  y   active

Pivot Details : Row Label - Country. (Works fine) Colum Label - Team (Unable to add this using POI) Report Filter - Player Status (Works fine) & Values - Count of Name (Works fine)

Whenever I use the addColumLabel() function the column used is added to Values! Should I use the addDataColumn() function, if so, how shoul it be used ?

1
Could you post the code that you're trying which isn't working? - Gagravarr
I don't actually know the exact function to use! I've been using the addColumLabel() function, but that seems to add colums only to the 'Values' part of the pivot. I'm unable to add Colums to 'Column Label'. - Antho Christen
should I use the addDataColumn function? I dont have any documentation on what that function is supposed to do, and the Documentation in Apache-POI doesn't say much as well! - Antho Christen
@Gagravarr - any suggestions? - Antho Christen
Try reading the unit tests which use it? - Gagravarr

1 Answers

7
votes

I rewrite addDataColumn method as below and it could add columnLabels properly.

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());
}