Apache POI : Excel Pivot Table - Row Label

2019-08-15 23:35发布

问题:

I have a requirement to create a excel sheet in JAVA as below :

I am not able to create a row label with multiple columns side by side ( menus and submenus filter ).

Instead of displaying the submenu in different column, its coming under the menu column.

Below is the piece of code which i have written :

XSSFSheet sheet = my_xlsx_workbook.getSheetAt(0); 
    AreaReference a=new AreaReference("A1:G7");
    CellReference b=new CellReference("I5");
    XSSFPivotTable pivotTable = sheet.createPivotTable(a,b);
    pivotTable.addReportFilter(0);
    pivotTable.addReportFilter(1);
    pivotTable.addRowLabel(2);
    pivotTable.addRowLabel(3);
    pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 4, "Sum");   

But its getting wrongly displayed as below :

Can someone please help me ?

回答1:

Since the format is XML it is easy to check what is needed. Unpack the Zip xlsx and look in the /xl/pivotTables/pivotTable1.xml.

Then: https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFPivotTable.html#getCTPivotTableDefinition%28%29 and http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/spreadsheetml/x2006/main/CTPivotTableDefinition.java.

    AreaReference a=new AreaReference(new CellReference("A1"), new CellReference("E7"));
    CellReference b=new CellReference("I5");
    XSSFPivotTable pivotTable = sheet.createPivotTable(a,b);
    pivotTable.addReportFilter(0);
    pivotTable.addReportFilter(1);
    pivotTable.addRowLabel(2);

pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).setOutline(false);

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