Java 使用ApachePOI将父列添加到Excel数据透视表
我试图使用ApachePOI在Excel中创建一个数据透视表,其中包含从数据库检索到的数据。 目前,我可以在透视表上创建普通列标签,但我希望能够添加父列表 这就是我希望我的桌子的外观: 以下是我创建透视表的方式:Java 使用ApachePOI将父列添加到Excel数据透视表,java,excel,apache-poi,pivot-table,Java,Excel,Apache Poi,Pivot Table,我试图使用ApachePOI在Excel中创建一个数据透视表,其中包含从数据库检索到的数据。 目前,我可以在透视表上创建普通列标签,但我希望能够添加父列表 这就是我希望我的桌子的外观: 以下是我创建透视表的方式: XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference( fromSheet.getSheetName() + "!" + tableRange), new CellReference(
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());
}
publicstaticvoidaddColumnLabels(XSSFPivotTable数据透视表,int-columnIndex){
AreaReference-pivotArea=getPivotArea(数据透视表);
int-lastColIndex=pivotArea.getLastCell().getCol()-pivotArea.getFirstCell().getCol();
如果(columnIndex>LastColinIndex&&columnIndex<0){
抛出新的IndexOutOfBoundsException();
}
CTPivotFields数据透视字段=数据透视表。getCTPivotTableDefinition().getPivotFields();
CTPivotField-pivotField=CTPivotField.Factory.newInstance();
CTItems items=pivotField.addNewItems();
数据透视字段.setAxis(stataxis.AXIS_COL);
pivotField.setShowAll(假);
对于(int i=0;i