Java – insert column labels into PivotTables using Apache POI?

I created a PivotTable using Apache POI 3.11 like this:

FileInputStream file = new FileInputStream(new File(path+fname));

XSSFWorkbook workbook = new  XSSFWorkbook(file);

XSSFSheet sheet = workbook.getSheetAt(0);
//area of pivot data
AreaReference a=new AreaReference("A1:J4");

CellReference b=new CellReference("N5");    
XSSFPivotTable pivotTable = sheet.createPivotTable(a,b);

//insert row
pivotTable.addRowLabel(3);
pivotTable.addRowLabel(6);

//insert column
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT,5);

//export
FileOutputStream output_file = 
   new FileOutputStream(new File(path+"POI_XLS_Pivot_Example.xlsx")); 
workbook.write(output_file);//write excel document to output stream
output_file.close(); //close the file

When the report is generated, it displays the rows correctly But it does not display column labels:

I want to display column labels in my PivotTable report as follows:

img http://www.pivot-table.com/wp-content/uploads/2010/12/calculateditem04.png

Who knows the solution to this problem?

thank you.

Solution

The following method (slightly modified version of xssfpivottable.addrowlabel) adds a "normal" perspective column label:

public static void addColLabel(XSSFPivotTable pivotTable,int columnIndex) {
    AreaReference pivotArea = new AreaReference(pivotTable.getPivotCacheDeFinition().getCTPivotCacheDeFinition()
            .getCacheSource().getWorksheetSource().getRef());
    int lastRowIndex = pivotArea.getLastCell().getRow() - pivotArea.getFirstCell().getRow();
    int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol();

    if (columnIndex > lastColIndex) {
        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 <= lastRowIndex; i++) {
        items.addNewItem().setT(STItemType.DEFAULT);
    }
    items.setCount(items.sizeOfItemArray());
    pivotFields.setPivotFieldArray(columnIndex,pivotField);

    CTColFields rowFields;
    if (pivotTable.getCTPivotTableDeFinition().getColFields() != null) {
        rowFields = pivotTable.getCTPivotTableDeFinition().getColFields();
    } else {
        rowFields = pivotTable.getCTPivotTableDeFinition().addNewColFields();
    }

    rowFields.addNewField().setX(columnIndex);
    rowFields.setCount(rowFields.sizeOfFieldArray());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>