Documents for Excel, Java Edition Documentation
Features / Pivot Table / Pivot Table Settings
In This Topic
    Pivot Table Settings
    In This Topic

    You can modify the settings of the pivot table added in a worksheet by referring to the following tasks:

    Configure pivot table fields

    The fields of a pivot table can be configured using the methods of the IPivotCaches interface and IPivotTables interface, as shown in the example code shared below.

    Java
    Copy Code
    Object sourceData = new Object[][] { { "Order ID", "Product", "Category", "Amount", "Date", "Country" },
            { 1, "Carrots", "Vegetables", 4270, new GregorianCalendar(2018, 0, 6), "United States" },
            { 2, "Broccoli", "Vegetables", 8239, new GregorianCalendar(2018, 0, 7), "United Kingdom" },
            { 3, "Banana", "Fruit", 617, new GregorianCalendar(2018, 0, 8), "United States" },
            { 4, "Banana", "Fruit", 8384, new GregorianCalendar(2018, 0, 10), "Canada" },
            { 5, "Beans", "Vegetables", 2626, new GregorianCalendar(2018, 0, 10), "Germany" },
            { 6, "Orange", "Fruit", 3610, new GregorianCalendar(2018, 0, 11), "United States" },
            { 7, "Broccoli", "Vegetables", 9062, new GregorianCalendar(2018, 0, 11), "Australia" },
            { 8, "Banana", "Fruit", 6906, new GregorianCalendar(2018, 0, 16), "New Zealand" },
            { 9, "Apple", "Fruit", 2417, new GregorianCalendar(2018, 0, 16), "France" },
            { 10, "Apple", "Fruit", 7431, new GregorianCalendar(2018, 0, 16), "Canada" },
            { 11, "Banana", "Fruit", 8250, new GregorianCalendar(2018, 0, 16), "Germany" },
            { 12, "Broccoli", "Vegetables", 7012, new GregorianCalendar(2018, 0, 18), "United States" },
            { 13, "Carrots", "Vegetables", 1903, new GregorianCalendar(2018, 0, 20), "Germany" },
            { 14, "Broccoli", "Vegetables", 2824, new GregorianCalendar(2018, 0, 22), "Canada" },
            { 15, "Apple", "Fruit", 6946, new GregorianCalendar(2018, 0, 24), "France" }, };
    
    IWorksheet worksheet = workbook.getWorksheets().get(0);
    worksheet.getRange("A1:F16").setValue(sourceData);
    worksheet.getRange("A:F").setColumnWidth(15);
    IPivotCache pivotcache = workbook.getPivotCaches().create(worksheet.getRange("A1:F16"));
    IPivotTable pivottable = worksheet.getPivotTables().add(pivotcache, worksheet.getRange("H7"), "pivottable1");
    worksheet.getRange("D2:D16").setNumberFormat("$#,##0.00");
    worksheet.getRange("I9:O11").setNumberFormat("$#,##0.00");
    worksheet.getRange("H:O").setColumnWidth(12);
            
    // config pivot table's fields
    IPivotField field_Category = pivottable.getPivotFields().get("Category");
    field_Category.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Product = pivottable.getPivotFields().get("Product");
    field_Product.setOrientation(PivotFieldOrientation.ColumnField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get("Amount");
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    
    IPivotField field_Country = pivottable.getPivotFields().get("Country");
    field_Country.setOrientation(PivotFieldOrientation.PageField);

    Add field function

    In order to add field function in a pivot table, refer to the following example code.

    Java
    Copy Code
    // Change or set data field's summarize function.
    field_Amount.setFunction(ConsolidationFunction.Average);

    Filter Pivot Table

    In order to execute the filter operation on a pivot table, refer to the following example code.

    Java
    Copy Code
    IPivotField field_Product = pivottable.getPivotFields().get(1);
    field_Product.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get(3);
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    
    IPivotField field_Country = pivottable.getPivotFields().get(5);
    field_Country.setOrientation(PivotFieldOrientation.PageField);
    
    // Apply row field filter.
    field_Product.getPivotItems().get("Apple").setVisible(false);
    field_Product.getPivotItems().get("Beans").setVisible(false);
    field_Product.getPivotItems().get("Orange").setVisible(false);
    
    // Apply page filter.
    field_Country.getPivotItems().get("United States").setVisible(false);
    field_Country.getPivotItems().get("Canada").setVisible(false);

    Manage Pivot Field Level

    In order to manage the field level of a pivot table, refer to the following example code.

    Java
    Copy Code
    // Product in level 1.
    IPivotField field_product = pivottable.getPivotFields().get("Product");
    field_product.setOrientation(PivotFieldOrientation.RowField);
    
    // Category in level 2.
    IPivotField field_category = pivottable.getPivotFields().get("Category");
    field_category.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get(3);
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    
    // Category will be in level 1 and product will be in level 2.
    field_product.setPosition(1);
    field_category.setPosition(0);

    Manage Grand Total Visibility Settings

    The Grand total in pivot table helps in analyzing the total sum of the data in the pivot table. You can display or hide the grand total for the row or column field by setting the visibility of ColumnGrand and RowGrand properties of the IPivotTable interface. These properties take boolean values and are set to true by default. For example, if you want to display the grand total only for rows, then set the RowGrand method to true and ColumnGrand to false.

    Refer to the following example code to manage the visibility settings of the grand total field.

    Java
    Copy Code
    // Set the PivotTable report to show grand totals for columns & rows
    pivottable.setColumnGrand(true);
    pivottable.setRowGrand(true);

    Change Row Axis Layout

    The display of pivot table can be changed to any desired layout using the LayoutRowType enumeration. The following options are provided by this enumeration:

    Note: The SubtotalLocationType enumeration can only be set to Bottom if the LayoutRowType is set to TabularRow.

    Refer to the following example code to set the row axis layout of the pivot table to TabularRow.

    Java
    Copy Code
    // Set the PivotTable LayoutRowType to Tabular Row
    pivottable.setRowAxisLayout(LayoutRowType.TabularRow);

    Change Pivot Table Layout

    The different layouts of a pivot table makes it more flexible and convenient to analyse its data. GcExcel supports the following pivot table layouts:

    In addition to these, you can also choose to insert blank rows, set the position of subtotals, show all items or to repeat any item in the pivot table layouts.

    Refer to the following example code to set the layout of pivot table and additional options.

    Java
    Copy Code
    // Set pivot table layout
    field_Category.setLayoutForm(LayoutFormType.Tabular);
    field_Category.setLayoutBlankLine(true);
    
    field_Country.setLayoutForm(LayoutFormType.Outline);
    field_Country.setLayoutCompactRow(false);
    
    // Set subtotal location
    field_Country.setLayoutSubtotalLocation(SubtotalLocationType.Bottom);
    field_Country.setShowAllItems(true);

    Rename Pivot Table Fields

    Sometimes, the pivot table fields are not easily comprehendible and hence can be renamed to meaningful and easily understandable names.

    Refer to the following example code to rename the pivot table fields.

    Java
    Copy Code
    // config pivot table's fields
    IPivotField field_Date = pivottable.getPivotFields().get("Date");
    field_Date.setOrientation(PivotFieldOrientation.PageField);
    
    IPivotField field_Category = pivottable.getPivotFields().get("Category");
    field_Category.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Product = pivottable.getPivotFields().get("Product");
    field_Product.setOrientation(PivotFieldOrientation.ColumnField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get("Amount");
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    field_Amount.setNumberFormat("$#,##0.00");
    
    IPivotField field_Country = pivottable.getPivotFields().get("Country");
    field_Country.setOrientation(PivotFieldOrientation.RowField);
    
    // Renaming DataField "Sum of Amount" to "Amount Total"
    pivottable.getDataFields().get(0).setName("Amount Total");

    Refresh Pivot Table

    In order to refresh a pivot table, refer to the following example code.

    Java
    Copy Code
    IPivotField field_Product = pivottable.getPivotFields().get("Product");
    field_Product.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get(3);
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    
    // change pivot cache's source data.
    worksheet.getRange("D8").setValue(3000);
    
    // sync cache's data to pivot table.
    worksheet.getPivotTables().get(0).refresh();

    Modify Pivot Table

    In order to modify a pivot table, refer to the following example code.

    Java
    Copy Code
    // Defining source data
    Object sourceData = new Object[][] 
    { 
      { "Order ID", "Product", "Category", "Amount", "Date", "Country" },
      { 1, "Carrots", "Vegetables", 4270, new GregorianCalendar(2018, 0, 6),"United States" },
      { 2, "Broccoli", "Vegetables", 8239, new GregorianCalendar(2018, 0, 7),"United Kingdom" },
      { 3, "Banana", "Fruit", 617, new GregorianCalendar(2018, 0, 8),"United States" },
      { 4, "Banana", "Fruit", 8384, new GregorianCalendar(2018, 0, 10),"Canada" },
      { 5, "Beans", "Vegetables", 2626, new GregorianCalendar(2018, 0, 10),"Germany" },
      { 6, "Orange", "Fruit", 3610, new GregorianCalendar(2018, 0, 11),"United States" },
      { 7, "Broccoli", "Vegetables", 9062, new GregorianCalendar(2018, 0, 11),"Australia" },
      { 8, "Banana", "Fruit", 6906, new GregorianCalendar(2018, 0, 16),"New Zealand" },
      { 9, "Apple", "Fruit", 2417, new GregorianCalendar(2018, 0, 16),"France" },
      { 10, "Apple", "Fruit", 7431, new GregorianCalendar(2018, 0, 16),"Canada" },
      { 11, "Banana", "Fruit", 8250, new GregorianCalendar(2018, 0, 16),"Germany" },
      { 12, "Broccoli", "Vegetables", 7012, new GregorianCalendar(2018, 0, 18),"United States" },
      { 13, "Carrots", "Vegetables", 1903, new GregorianCalendar(2018, 0, 20),"Germany" },
      { 14, "Broccoli", "Vegetables", 2824, new GregorianCalendar(2018, 0, 22),"Canada" },
      { 15, "Apple", "Fruit", 6946, new GregorianCalendar(2018, 0, 24),"France" }, 
    };
            
    // Initialize workbook and fetch the default worksheet
    Workbook workbook = new Workbook();
    IWorksheet worksheet = workbook.getWorksheets().get(0);
            
    // Assigning data to the range
    worksheet.getRange("A1:F16").setValue(sourceData);
            
    // Creating pivot table and modifying it
    IPivotCache pivotcache = workbook.getPivotCaches().create(worksheet.getRange("A1:F16"));
    IPivotTable pivottable = worksheet.getPivotTables().add(pivotcache, 
    worksheet.getRange("I2"), "pivottable1");
            
    worksheet.getRange("D2:D16").setNumberFormat("$#,##0.00");
    worksheet.getRange("J4:J17, J9:J33").setNumberFormat("$#,##0.00");
    
    // Configure pivot table's fields
    IPivotField field_Product = pivottable.getPivotFields().get(1);
    field_Product.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Category = pivottable.getPivotFields().get(2);
    field_Category.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get(3);
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    
    // Modify subtotals for pivot field.
    field_Category.setSubtotals(EnumSet.of(SubtotalType.Sum, SubtotalType.Count, 
    SubtotalType.Average,SubtotalType.Max, SubtotalType.Min, SubtotalType.CountNums, 
    SubtotalType.StdDev, SubtotalType.StdDevP,SubtotalType.Var, SubtotalType.VarP));
            
    worksheet.getRange("E:E").setColumnWidth(12);
    worksheet.getRange("J:J").setColumnWidth(20);

    Apply Different Calculations on a Pivot Field

    In GcExcel, you can add a pivot table field to a pivot table multiple times by applying various calculation functions on it. These functions include sum, average, min, max, count etc. The final pivot table output will contain multiple data fields based on the calculations applied over the pivot table field.

    Refer to the following example code to add a pivot table field as multiple data fields by applying different calculation functions.

    Java
    Copy Code
    // Config pivot table's fields
    IPivotField field_Category = pivottable.getPivotFields().get("Category");
    field_Category.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Product = pivottable.getPivotFields().get("Product");
    field_Product.setOrientation(PivotFieldOrientation.RowField);
    
    // Sum function on Amount field
    IPivotField field_Amount = pivottable.getPivotFields().get("Amount");
    pivottable.addDataField(field_Amount, "sum amount", ConsolidationFunction.Sum);
    
    // Count function on Amount field
    IPivotField field_Amount2 = pivottable.getPivotFields().get("Amount");
    pivottable.addDataField(field_Amount2, "count amount", ConsolidationFunction.Count);

    The output of above example code when viewed in Excel, looks like below:

     

    Defer Layout Update

    In case of huge amount of data, the performance of a pivot table might get affected while updating its layout by adding or moving fields in the different areas of a pivot table.

    GcExcel provides setDeferLayoutUpdate method which improves the performance of a pivot table by deferring its layout updates. When set to true, the pivot table is recalculated only after all the fields are added or moved instead of getting recalculated after each change. You can choose to update the pivot table output after making all the changes by calling the update method.

    Refer to the following example code to defer layout updates to a pivot table.

    Java
    Copy Code
    // Defer layout update
    pivottable.setDeferLayoutUpdate(true);
    
    // Config pivot table's fields
    IPivotField field_Category = pivottable.getPivotFields().get("Category");
    field_Category.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Product = pivottable.getPivotFields().get("Product");
    field_Product.setOrientation(PivotFieldOrientation.ColumnField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get("Amount");
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    
    // Update the pivottable.
    pivottable.update();

    Use Pivot Table Options

    GcExcel supports the following layout and formatting options in a pivot table:

    Refer to the following example code to set various layout and format options in a pivot table.

    Java
    Copy Code
    pivottable.setPageFieldOrder(Order.OverThenDown);
    pivottable.setPageFieldWrapCount(2);
    pivottable.setCompactRowIndent(2);
    
    pivottable.setErrorString("Error");
    pivottable.setNullString("Empty");
    
    pivottable.setDisplayErrorString(true);
    pivottable.setDisplayNullString(true);

    Sort Pivot Table Fields

    GcExcel supports sorting data fields in a pivot table by using autoSort method and defining ascending or descending as its sort order.

    You can also retrieve the name of data field used to sort the specified PivotTable field by using autoSortField method and its sorting order by using autoSortOrder method. The position of an item in its field can also be set or retrieved by using the setPosition or getPosition method of IPivotItem interface.

    Refer to the following example code to sort 'Product' field in a pivot table.

    Java
    Copy Code
    // Sort the product items
    field_Product.autoSort(SortOrder.Descending);

    Retrieve Pivot Table Ranges

    The structure of a pivot table report is comprised of different ranges. In order to retrieve a specific range of pivot table, it is important to understand the structure of a pivot table.

    Pivot table report

     As can be observed from the above screenshot, the structure of a pivot table can be explained as:

    GcExcel provides API to retrieve the detailed ranges of a pivot table to apply any operation or style on them to make the result more readable and distinguishable. Detailed pivot table ranges which can be retrieved are:

    Refer to the following example code to get a specific range and set its style in a pivot table report.

    Java
    Copy Code
    // Get detail range and set style.
    for (IPivotLine item : pivottable.getPivotRowAxis().getPivotLines()) {
        if (item.getLineType() == PivotLineType.Subtotal) {
            item.getPivotLineCells().get(0).getRange().getInterior().setColor(Color.GetGreenYellow());
        }
    }

    The output of above code example when viewed in Excel, looks like below: 

    Pivot table report output

    Note: Style applied to a pivot table is lost if the pivot table is changed in any way.

    Get Pivot Table Data

    GcExcel Java provides GETPIVOTDATA function which queries the pivot table to fetch data as per the specified parameters. The function has two required arguments, that is, name of the data field that contains the required data and range of cells in a PivotTable. You can also use the IRange.generateGetPivotDataFunction method to generate the GETPIVOTDATA function automatically on selecting a cell in the PivotTable while entering the function. As the function returns the data based on the pivot table structure instead of cell references, always correct data is returned even if there is change in layout.

    Java
    Copy Code
    IWorksheet worksheet2 = workbook.getWorksheets().add();
    worksheet.getRange("H25").setFormula(worksheet.getRange("G6").generateGetPivotDataFunction(worksheet2.getRange("A1")));
    worksheet2.getRange("H24").setFormula("=GETPIVOTDATA(\"Amount\",Sheet1!$A$1,\"Category\",\"Mobile\",\"Country\",\"Australia\")");

    Set Conditional Formatting

    Refer to the following example code to set conditional formatting in last row of a pivot table report by setting cell color when the values are above average.

    Java
    Copy Code
    // set condional format to the last row
    int rowCount = pivottable.getDataBodyRange().getRowCount();
    IAboveAverage averageCondition = pivottable.getDataBodyRange().getRows().get(rowCount - 1).getFormatConditions()
            .addAboveAverage();
    averageCondition.setAboveBelow(AboveBelow.AboveAverage);
    averageCondition.getInterior().setColor(Color.GetPink());
    
    // save to an excel file
    workbook.save("PTConditionalFormat.xlsx");

    Note: Conditional formatting applied to a pivot table is lost if the pivot table is changed in any way.

    Disable Automatic Grouping of Date/Time Columns

    The Date/Time columns in a pivot table are grouped together by default. GcExcel allows you to disable this grouping by setting setAutomaticGroupDateTimeInPivotTable method to false before creating the pivot cache while creating a pivot table.

    When AutomaticGroupDateTimeInPivotTable = False When AutomaticGroupDateTimeInPivotTable = True (default)

    Refer to the following example code to disable automatic grouping of date/time columns.

    Java
    Copy Code
    // Set false to group date/time fields in PivotTable automatically
    workbook.getOptions().getData().setAutomaticGroupDateTimeInPivotTable(false);

    Expand or Collapse Pivot Table Fields

    GcExcel provides setShowDetail method in IPivotItem interface which allows you to expand or collapse the outline of pivot table fields. The default value of the method is True which shows the expanded state of pivot table fields. However, it can be set to False to display the collapsed state.

    Refer to the following example code to set collapsed state of two pivot table fields.

    C#
    Copy Code
    worksheet.getRange("F1:K16").setValue(sourceData);
    worksheet.getRange("F:K").setColumnWidth(15);
    IPivotCache pivotcache = workbook.getPivotCaches().create(worksheet.getRange("F1:K16"));
    IPivotTable pivottable = worksheet.getPivotTables().add(pivotcache, worksheet.getRange("A1"), "pivottable1");
            
    // Config pivot table's fields
    IPivotField field_Date = pivottable.getPivotFields().get("Date");
    field_Date.setOrientation(PivotFieldOrientation.PageField);
    
    IPivotField field_Category = pivottable.getPivotFields().get("Category");
    field_Category.setOrientation(PivotFieldOrientation.ColumnField);
    
    IPivotField field_Country = pivottable.getPivotFields().get("Country");
    field_Country.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Product = pivottable.getPivotFields().get("Product");
    field_Product.setOrientation(PivotFieldOrientation.RowField);
    
    IPivotField field_Amount = pivottable.getPivotFields().get("Amount");
    field_Amount.setOrientation(PivotFieldOrientation.DataField);
    field_Amount.setNumberFormat("$#,##0.00");
    
    // Set not to show Canandian and German details.
    field_Country.getPivotItems().get("Canada").setShowDetail(false);
    field_Country.getPivotItems().get("Germany").setShowDetail(false);
    
    worksheet.getRange("A:I").getEntireColumn().autoFit();
    
    //save to an excel file
    workbook.save("SetShowDetail.xlsx");