Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache POI Add Column Label

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 ?

like image 819
Antho Christen Avatar asked Mar 15 '23 22:03

Antho Christen


1 Answers

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());
}
like image 111
王昱文 Avatar answered Mar 23 '23 12:03

王昱文