How to collapse all fields in pivot table from java?

回眸只為那壹抹淺笑 提交于 2019-12-11 19:26:22

问题


I am creating a pivot table using apache poi in JAVA and it generates a pivot table like below with all rows expanded by default
How do I generate Pivote table will all rows collapsed like below from java Code.

Thank you in advance.
Code used for generating pivot table

            AreaReference a=new AreaReference("A1:G5667", null);
            CellReference b=new CellReference("A1");
            XSSFSheet pivot_sheet=workbook.createSheet("Pivot_table");
            XSSFPivotTable pivotTable = pivot_sheet.createPivotTable(a,b,spreadsheet);
            pivotTable.addRowLabel(6);
            pivotTable.addRowLabel(0);
            pivotTable.addRowLabel(2);
            pivotTable.addRowLabel(3);
            pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 4,"Sum");

回答1:


The code you are providing cannot lead to the first displayed result since it does not set different column labels. It only adds column E as data consolidating column.

But I will nevertheless try answering. So I assume that column G shall be first row label. Column A shall be second row label, which shall be collapsed, Column C shall be the third row label. But column D is the column containing the "APR 2018", "MAY 2018", "JUN 2018" and shall be column label then.

The problem is that apache poi is not analyzing the content while creating the pivot table. So it simply adds as much "default" pivot field items for each pivot field as rows are in the data range. And it only creates a very rudimentary pivot cache. That works as long as we only use defaults since Excel then does correcting this while rendering the pivot table. But if we need others than the default, collapsing row labels for example, then this fails.

So we need unique contents in column A for having a count of needed pivot items and for creating the pivot cache properly. Then we need changing as much pivot field items from "default" to real pivot field items as different contents are in column A. Those pivot field items must have attribute x set which points to the pivot cache. And the pivot cache must be created properly having the single unique contents in column A. Also the attribute sd must be set false which indicates that the details are hidden for this item.

Complete Example:

Excel:

Code:

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;

import java.io.FileOutputStream;
import java.io.FileInputStream;

import java.util.List;
import java.util.Set;
import java.util.HashSet;

class ExcelPivotTableTest {

 public static void main(String[] args) throws Exception{

  XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("PivotExample.xlsx"));
  XSSFSheet dataSheet = workbook.getSheet("Data");

  XSSFSheet pivotSheet = workbook.createSheet("Pivot");

  AreaReference a = new AreaReference("A1:G" + (dataSheet.getLastRowNum() + 1), SpreadsheetVersion.EXCEL2007);
  CellReference b = new CellReference("A1");

  XSSFPivotTable pivotTable = pivotSheet.createPivotTable(a, b, dataSheet);

  pivotTable.addRowLabel(6); //column G as first row label

  pivotTable.addRowLabel(0); //column A as second row label - shall be collapsed

  //we need unique contents in column A for creating the pivot cache
  Set<String> colAValues = new HashSet<String>();
  for (int r = 1; r < dataSheet.getLastRowNum() + 1; r++) {
   Row row = dataSheet.getRow(r);
   if (row != null) {
    Cell cell = row.getCell(0);
    if (cell != null) {
     colAValues.add(cell.toString());
    }
   }
  }

  //now go through all pivot items of first pivot field 
  List<org.openxmlformats.schemas.spreadsheetml.x2006.main.CTItem> itemList = 
   pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemList();
  int i = 0; 
  org.openxmlformats.schemas.spreadsheetml.x2006.main.CTItem item = null;
  for (String value : colAValues) { //as long as there are different column A values
   item = itemList.get(i);
   item.unsetT(); //unset the type "default"
   item.setX(i++); //set x
   pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields()
    .getCacheFieldArray(0).getSharedItems().addNewS().setV(value); //create pivot cache entry
   item.setSd(false); //set sd false = indicates that the details are hidden for this item
  }
  while (i < itemList.size()) {
   item = itemList.get(i++);
   item.setSd(false);
  }


  pivotTable.addRowLabel(2); //column C as third row label

  pivotTable.addRowLabel(3); //column D as row label - shall be column label instead
  //do changing column D to a col label
  pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(3)
   .setAxis(org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis.AXIS_COL); //AXIS_COL
  //remove column D from RowFields
  pivotTable.getCTPivotTableDefinition().getRowFields().removeField(3); 
  pivotTable.getCTPivotTableDefinition().getRowFields().setCount(3);
  //create ColFields for column D
  pivotTable.getCTPivotTableDefinition().addNewColFields().addNewField().setX(3); 
  pivotTable.getCTPivotTableDefinition().getColFields().setCount(1);

  pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 4, "Sum");

  workbook.write(new FileOutputStream("PivotExample_New.xlsx"));
  workbook.close();

 }
}

This code needs ooxml-schemas-1.3.jar as mentioned in apache poi FAQ.

Result:



来源:https://stackoverflow.com/questions/52058700/how-to-collapse-all-fields-in-pivot-table-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!