使用Apache POI将父列添加到Excel数据透视表

我正在尝试使用Apache-POI在Excel中用从数据库中检索的数据创build数据透视表。 目前我可以在数据透视表上创build正常的列标签,但我想能够添加父列表。

这是我希望我的表看起来如何: 在这里输入图像说明

这是我如何创build数据透视表:

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"); 

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

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

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