Document Solutions for Excel, .NET Edition | Document Solutions
Features / Pivot Table / Pivot Table Settings
In This Topic
    Pivot Table Settings
    In This Topic

    You can modify the setting of the pivot table created in a spreadsheet by performing the following tasks:

    Configure Pivot Table Fields

    You can configure the fields of your pivot table using the properties and methods of the IPivotCaches interface and IPivotTables interface.

    Refer to the following example code to configure the pivot table fields in a worksheet.

    C#
    Copy Code
    //Source data for PivotCache
    object[,] sourceData = new object[,] {
    { "Order ID", "Product",  "Category",   "Amount", "Date",                    "Country" },
    { 1,          "Carrots",  "Vegetables",  4270,    new DateTime(2012, 1, 6),  "United States" },
    { 2,          "Broccoli", "Vegetables",  8239,    new DateTime(2012, 1, 7),  "United Kingdom" },
    { 3,          "Banana",   "Fruit",       617,     new DateTime(2012, 1, 8),  "United States" },
    { 4,          "Banana",   "Fruit",       8384,    new DateTime(2012, 1, 10), "Canada" },
    { 5,          "Beans",    "Vegetables",  2626,    new DateTime(2012, 1, 10), "Germany" },
    { 6,          "Orange",   "Fruit",       3610,    new DateTime(2012, 1, 11), "United States" },
    { 7,          "Broccoli", "Vegetables",  9062,    new DateTime(2012, 1, 11), "Australia" },
    { 8,          "Banana",   "Fruit",       6906,    new DateTime(2012, 1, 16), "New Zealand" },
    { 9,          "Apple",    "Fruit",       2417,    new DateTime(2012, 1, 16), "France" },
    { 10,         "Apple",    "Fruit",       7431,    new DateTime(2012, 1, 16), "Canada" },
    { 11,         "Banana",   "Fruit",       8250,    new DateTime(2012, 1, 16), "Germany" },
    { 12,         "Broccoli", "Vegetables",  7012,    new DateTime(2012, 1, 18), "United States" },
    { 13,         "Carrots",  "Vegetables",  1903,    new DateTime(2012, 1, 20), "Germany" },
    { 14,         "Broccoli", "Vegetables",  2824,    new DateTime(2012, 1, 22), "Canada" },
    { 15,         "Apple",    "Fruit",       6946,    new DateTime(2012, 1, 24), "France" },
    };
    
    //Initialize the WorkBook and fetch the default WorkSheet
    Workbook workbook = new Workbook();
    IWorksheet worksheet = workbook.Worksheets[0];
    // Assigning data to the range
    worksheet.Range["A1:F16"].Value = sourceData;
    // Creating pivot
    var pivotcache = workbook.PivotCaches.Create(worksheet.Range["A1:F16"]);
    var pivottable = worksheet.PivotTables.Add(pivotcache, worksheet.Range["L7"], "pivottable1");
                
    // Configuring pivot table fields
    var field_Category = pivottable.PivotFields["Category"];
    field_Category.Orientation = PivotFieldOrientation.RowField;
    
    var field_Product = pivottable.PivotFields["Product"];
    field_Product.Orientation = PivotFieldOrientation.ColumnField;
    
    var field_Amount = pivottable.PivotFields["Amount"];
    field_Amount.Orientation = PivotFieldOrientation.DataField;
    
    var field_Country = pivottable.PivotFields["Country"];
    field_Country.Orientation = PivotFieldOrientation.PageField;

    Add Field Function

    Refer to the following example code to add field function in a pivot table.

    C#
    Copy Code
    //Set field amount function
    field_Amount.Function = ConsolidationFunction.Average;

    Filter Pivot Table

    Refer to the following example code to filter a pivot table.

    C#
    Copy Code
    var field_product = pivottable.PivotFields[1];
    field_product.Orientation = PivotFieldOrientation.RowField;
    
    var field_Amount = pivottable.PivotFields[3];
    field_Amount.Orientation = PivotFieldOrientation.DataField;
    
    var field_Country = pivottable.PivotFields[5];
    field_Country.Orientation = PivotFieldOrientation.PageField;
    
    //row field filter.
    field_product.PivotItems["Apple"].Visible = false;
    field_product.PivotItems["Beans"].Visible = false;
    field_product.PivotItems["Orange"].Visible = false;
    
    //page filter.
    field_Country.PivotItems["United States"].Visible = false;
    field_Country.PivotItems["Canada"].Visible = false;

    Manage Pivot Field Level

    Refer to the following example code to manage the field level of a pivot table.

    C#
    Copy Code
    //product in level 1.
    var field_product = pivottable.PivotFields["Product"];
    field_product.Orientation = PivotFieldOrientation.RowField;
    
    //category in level 2.
    var field_category = pivottable.PivotFields["Category"];
    field_category.Orientation = PivotFieldOrientation.RowField;
    
    var field_Amount = pivottable.PivotFields[3];
    field_Amount.Orientation = PivotFieldOrientation.DataField;
    
    //category will in level 1 and product in level 2.
    field_product.Position = 1;
    field_category.Position = 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 property to true and ColumnGrand to false.

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

    C#
    Copy Code
    // Set the PivotTable report to show grand totals for columns & rows
    pivottable.ColumnGrand = true;
    pivottable.RowGrand = 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.

    C#
    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. DsExcel 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.

    C#
    Copy Code
    //set pivot table layout
    field_Category.LayoutForm = LayoutFormType.Tabular;
    field_Category.LayoutBlankLine = true;
    
    field_Country.LayoutForm = LayoutFormType.Outline;
    field_Country.LayoutCompactRow = false;
    
    //set subtotal location
    field_Country.LayoutSubtotalLocation = SubtotalLocationType.Bottom;
    field_Country.ShowAllItems = 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.

    C#
    Copy Code
    //config pivot table's fields
    var field_Date = pivottable.PivotFields["Date"];
    field_Date.Orientation = PivotFieldOrientation.PageField;
    
    // Renaming PivotField "Category" to "Type of Category"
    var field_Category = pivottable.PivotFields["Category"];
    field_Category.Name = "Type of Category";
    field_Category.Orientation = PivotFieldOrientation.RowField;
    
    var field_Product = pivottable.PivotFields["Product"];
    field_Product.Orientation = PivotFieldOrientation.ColumnField;
    
    var field_Amount = pivottable.PivotFields["Amount"];
    field_Amount.Orientation = PivotFieldOrientation.DataField;
         
    
    var field_Country = pivottable.PivotFields["Country"];
    field_Country.Orientation = PivotFieldOrientation.RowField;
    
    // Renaming DataField "Sum of Amount" to "Amount Total"
    pivottable.DataFields[0].Name = "Amount Total";
    
    

    Refresh Pivot Table

    Refer to the following example code to refresh a pivot table.

    C#
    Copy Code
    var field_product = pivottable.PivotFields["Product"];
    field_product.Orientation = PivotFieldOrientation.RowField;
    
    var field_Amount = pivottable.PivotFields[3];
    field_Amount.Orientation = PivotFieldOrientation.DataField;
    
    //change pivot cache's source data.
    worksheet.Range["D8"].Value = 3000;
    
    //sync cache's data to pivot table.
    worksheet.PivotTables[0].Refresh();

    Apply Different Calculations on a Pivot Field

    In DsExcel, 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.

    C#
    Copy Code
    //config pivot table's fields
    var field_Category = pivottable.PivotFields["Category"];
    field_Category.Orientation = PivotFieldOrientation.RowField;
    
    var field_Product = pivottable.PivotFields["Product"];
    field_Product.Orientation = PivotFieldOrientation.RowField;
    
    //sum function on Amount field
    var field_Amount = pivottable.PivotFields["Amount"];
    pivottable.AddDataField(field_Amount, "sum amount", ConsolidationFunction.Sum);
    
    //count function on Amount field
    var field_Amount2 = pivottable.PivotFields["Amount"];
    pivottable.AddDataField(field_Amount2, "count amount", ConsolidationFunction.Count);

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

     

    Calculated Fields

    Calculated fields in pivot table refer to the data fields created by applying additional logic or formula on existing data fields of the underlying data source. These fields are especially useful when summary functions and custom calculations do not generate the desired output. For instance, an employee database of a company holds data about existing salary and performance rating of each employee. At year end, one can easily calculate the raised salary of employees by creating calculated field using salary and the rating field.

    In DsExcel, CalculatedFields property represents the collection of all calculated fields in a particular pivot table. You can use Add method of the ICalculatedFields interface to create a new calculated field in the pivot table. The Add method accepts fieldname and IPivotField.Formula property as its parameters to generate the calculated field. To remove a calculated field from the collection you can use the Remove method which takes target field name as its parameter.

    Refer to the following code to create a calculated field in the pivot table:

    C#
    Copy Code
    IWorksheet calculatedFieldSheet = workbook.Worksheets.Add();
    calculatedFieldSheet.Name = "CalculatedField";
            
    // Add pivot table.
    IPivotCache pivotCache = workbook.PivotCaches.Create(worksheet.Range["A1:F71"]);
    IPivotTable calculatedFieldTable = calculatedFieldSheet.PivotTables.Add(pivotCache, calculatedFieldSheet.Range["A1"]);
    calculatedFieldTable.PivotFields["Product"].Orientation = PivotFieldOrientation.RowField;
    calculatedFieldTable.PivotFields["Amount"].Orientation = PivotFieldOrientation.DataField;
    calculatedFieldTable.DataFields["Sum of Amount"].NumberFormat = "$#,##0_);($#,##0)";
            
    // Add calculated field.
    calculatedFieldTable.CalculatedFields.Add("Tax", "=IF(Amount > 1000, 3% * Amount, 0)");
            
    // Set calculated field as data field.
    calculatedFieldTable.PivotFields["Tax"].Orientation = PivotFieldOrientation.DataField;
    calculatedFieldTable.DataFields["Sum of Tax"].NumberFormat = "$#,##0_);($#,##0)";

    Calculated Items

    Calculated items are pivot table items that use custom formulas containing constants or refer to other items in the pivot table. These items can be added to the row or column field area of the pivot table but do not exist in the source data.

    In DsExcel, ICalculatedItems interface represents the collection of calculated items in a particular pivot table. You can fetch this collection of pivot items by using IPivotField.CalculatedItems method. To add calculated items to a pivot table, the ICalculatedItems interface provides Add method which accepts name and formula of the item as parameters. You can also use IPivotItem.Formula for setting the formula of a calculated item. To remove a calculated item from the ICalculatedItems collection, you can use Remove method which accepts name of the target field as parameter. Pivot cache manages all the calculated items, hence changing a calculated item affects all pivot tables using same cache in the current workbook. Also, any kind of addition, deletion or change in calculated item triggers the pivot table update.

    Note: An exception is thrown on:

    • Adding the same field to the data field section when a calculated item exists in the pivot table.
    • Adding calculated items when data field is having two or more same fields.
    • Adding a calculated item with a used name. Name parameter of calculated item is case-insensitive. Hence, pivot table considers the name “Formula” and “formula” as same.

    Refer to the following code to create calculated items in the pivot table:

    C#
    Copy Code
    // Get the calculated item for the specified field
    ICalculatedItems countryCalcItems = calculatedItemTable.PivotFields["Country"].CalculatedItems();
    ICalculatedItems productCalcItems = calculatedItemTable.PivotFields["Product"].CalculatedItems();
    
    // Add some calculated items using formulas
    countryCalcItems.Add("Oceania", "=Country[Australia]+Country[NewZealand]");
    countryCalcItems.Add("America", "=Country[Canada]");
    IPivotItem myPivotItem = countryCalcItems.Add("Europe", "=Country[France]");
    
    // Change the formula of the calculated item
    myPivotItem.Formula = "=Country[France]+Country[Germany]";
    
    // Add calculated item using constant value
    productCalcItems.Add("IPhone 13", "=2500");
    
    // Get the CalculatedItema count
    Console.Write("Calculated Items count : " + countryCalcItems.Count);
    
    // Remove a calculated item
    countryCalcItems.Remove("America");

    Show Value As

    While analyzing spreadsheet data, instead of comparing exact values, you may want to compare the values in terms of calculations. For instance, there are many ways to evaluate performance of a sales employee. You can compare his sales with target, sales as a percentage of total sales or sales in comparison to previous month's sale etc. To achieve these calculations easily, DsExcel provides "Show Value As" option which allows you to perform custom calculations in a pivot table by using several predefined formulas such as “% of Parent Total” or “% of Grand Total”.

    DsExcel.NET provides Calculation property of PivotField interface which accepts values from PivotFieldCalculation enumeration for setting the predefined calculations. You can also set the base field and base field item to perform these calculations using BaseField and BaseItem properties respectively.

    Refer to the following example code which demonstrates the value as percent of Australia.

    C#
    Copy Code
    IPivotTable percentOfTable = percentOfSheet.PivotTables.Add(pivotCache, percentOfSheet.Range["A1"]);
    percentOfTable.PivotFields["Category"].Orientation = PivotFieldOrientation.RowField;
    percentOfTable.PivotFields["Product"].Orientation = PivotFieldOrientation.RowField;
    percentOfTable.PivotFields["Country"].Orientation = PivotFieldOrientation.ColumnField;
    percentOfTable.PivotFields["Amount"].Orientation = PivotFieldOrientation.DataField;
            
    // set show value as, base field, base item.
    IPivotField percentOfTableDataField = percentOfTable.DataFields["Sum of Amount"];
    percentOfTableDataField.Calculation = PivotFieldCalculation.PercentOf;
    percentOfTableDataField.BaseField = "Country";
    percentOfTableDataField.BaseItem = "Australia";
            
    percentOfSheet.Range["A:I"].AutoFit();

    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.

    DsExcel provides DeferLayoutUpdate property 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.

    C#
    Copy Code
    //defer layout update
    pivottable.DeferLayoutUpdate = true;
    
    //config pivot table's fields
    var field_Category = pivottable.PivotFields["Category"];
    field_Category.Orientation = PivotFieldOrientation.RowField;
    
    var field_Product = pivottable.PivotFields["Product"];
    field_Product.Orientation = PivotFieldOrientation.ColumnField;
    
    var field_Amount = pivottable.PivotFields["Amount"];
    field_Amount.Orientation = PivotFieldOrientation.DataField;
    
    //must update the pivottable
    pivottable.Update();

    Use Pivot Table Options

    DsExcel 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.

    C#
    Copy Code
    //set layout and format options
    pivottable.PageFieldOrder = Order.OverThenDown;
    pivottable.PageFieldWrapCount = 2;
    
    pivottable.CompactRowIndent = 2;
    
    pivottable.ErrorString = "Error";
    pivottable.NullString = "Empty";
    
    pivottable.DisplayErrorString = true;
    pivottable.DisplayNullString = true;

    Sort Pivot Table Fields

    DsExcel 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 property and its sorting order by using AutoSortOrder property. The position of an item in its field can also be set or retrieved by using the Position property of IPivotItem interface.

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

    C#
    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:

    DsExcel 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.

    C#
    Copy Code
    //get detail range and set style
    foreach (var item in pivottable.PivotRowAxis.PivotLines)
    {
        if (item.LineType == PivotLineType.Subtotal)
        {
            item.PivotLineCells[0].Range.Interior.Color = Color.GreenYellow;
        }
    }

    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

    DsExcel.NET provides GETPIVOTDATA function which queries the pivot table to fetch data as per the specified parameters. The main advantage of using this function is that it ensures that the correct data is returned, even if the pivot table layout has changed.

    Syntax

    =GETPIVOTDATA(data_field, pivot_table, [field1, item1, field2, item2],…)

    GETPIVOTDATA function can be implemented to return a single cell value or a dynamic array depending on the parameters we are passing. To retrieve a single cell value, name of the data field and pivot table are mandatory parameters. While the third parameter which is a combination of field names and item names, is optional. However, for retrieving a dynamic array, all three parameters are required and the item name supports array like {“Canada”, “US”, “France”) or a range reference like A1:A3. Also, you must use IRange.Formula2{get;set;} for GETPIVOTDATA function to return a dynamic array which is spilled across a range. For ease of use, you can also automatically generate GETPIVOTDATA function by using the IRange.GenerateGetPivotDataFunction method. However, the GenerateGetPivotDataFunction method returns null when the IRange object is not a single cell.

    Refer to the following example code for GETPIVOTDATA function returning a single cell:

    C#
    Copy Code
    // GenerateGetPivotDataFunction method is used to generate formula automatically for the selected cell
    var worksheet2 = workbook.Worksheets.Add();
    worksheet.Range["H25"].Formula = worksheet.Range["G6"].GenerateGetPivotDataFunction(worksheet2.Range["A1"]);
    
    // Here, the GETPIVOTDATA function is used to fetch the desired result
    worksheet2.Range["H24"].Formula = @"=GETPIVOTDATA(""Amount"",Sheet1!$A$1,""Category"",""Mobile"",""Country"",""Australia"")";

    Refer to the following example code for GETPIVOTDATA function returning a dynamic array:

    C#
    Copy Code
    // Here, Formula2 is used along with GETPIVOTDATA to fetch the multiple values
    worksheet.Range["H10"].Formula2 = @"=GETPIVOTDATA(""Amount"",$A$1,""Category"",""Consumer Electronics"",""Country"",{""Canada"",""Germany"",""France""})";

    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.

    C#
    Copy Code
    // set condional format to the last row
    int rowCount = pivottable.DataBodyRange.RowCount;
    IAboveAverage averageCondition = pivottable.DataBodyRange.Rows[rowCount - 1].FormatConditions.AddAboveAverage();
    averageCondition.AboveBelow = AboveBelow.AboveAverage;
    averageCondition.Interior.Color = Color.Pink;

    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. DsExcel allows you to disable this grouping by setting AutomaticGroupDateTimeInPivotTable property 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.

    C#
    Copy Code
    // Set false to group date/time fields in PivotTable automatically
    workbook.Options.Data.AutomaticGroupDateTimeInPivotTable = false;

    Expand or Collapse Pivot Table Fields

    DsExcel provides ShowDetail property in IPivotItem interface which allows you to expand or collapse the outline of pivot table fields. The default value of the property 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.Range["A1:F16"].Value = sourceData;
    IPivotCache pivotCache = workbook.PivotCaches.Create(worksheet.Range["A1:F16"]);
    IPivotTable pivotTable = worksheet.PivotTables.Add(pivotCache, worksheet.Range["H7"], "pivottable1");
            
    pivotTable.PivotFields["Product"].Orientation = PivotFieldOrientation.RowField;
    pivotTable.PivotFields["Country"].Orientation = PivotFieldOrientation.RowField;
    pivotTable.PivotFields["Category"].Orientation = PivotFieldOrientation.ColumnField;
    pivotTable.PivotFields["Amount"].Orientation = PivotFieldOrientation.DataField;
            
    //Set collapsed state
    pivotTable.PivotFields["Product"].PivotItems["Banana"].ShowDetail = false;
    pivotTable.PivotFields["Product"].PivotItems["Carrots"].ShowDetail = false;
    
    workbook.Save("CollapsePivotFields.xlsx");