Click here to Skip to main content
15,881,852 members
Articles / Productivity Apps and Services / Microsoft Office

C# Excel - Pivot Table (Filter on Multiple Items)

Rate me:
Please Sign up or sign in to vote.
4.50/5 (9 votes)
18 Jul 2010CPOL 100.9K   3.3K   19   20
Add a filter to the Pivot Table where multiple items can be selected.

PivotTableMultiFilter_4.png

Introduction

This article describes a quick and easy example of communicating with Excel from .NET.

Using the code

I have included the complete source code in the attached example project. The sample illustrates how to:

  • Add reference to the Excel application
  • Add Excel Workbook/Sheets
  • Insert data to an Excel Worksheet
  • Add a Pivot Table to an Excel Worksheet
  • Add a filter to the Pivot Table where multiple items can be selected
  • Add a graphic chart to display the data from the Pivot Table

This code example is aimed at programmer having difficulty with C#/ Excel interop (especially related to the multiple item filter from the Pivot Table).

Examples

Adding a pivot table to an Excel Worksheet:

C#
//get a reference to the pivot chache
Excel.PivotCaches pch = m_objBook.PivotCaches();

//Activate the data sheet before adding the range to the pivot table
_m_objSheet_Data.Activate();

//add a pivot table reference to the sheet 
pch.Add(Excel.XlPivotTableSourceType.xlDatabase, "'" 
+ _m_objSheet_Data.Name + "'!A1:'" + _m_objSheet_Data.Name 
+ "'!J5").CreatePivotTable(_m_objSheet_Report_1.Cells[1, 1],
 "PivTbl_1", Type.Missing, Type.Missing);
Excel.PivotTable pvt = _m_objSheet_Report_1.PivotTables("PivTbl_1") 
                       as Excel.PivotTable;

////Column
//Excel.PivotField fld = ((Excel.PivotField)pvt.PivotFields("Target Language"));
//fld.Orientation = Excel.XlPivotFieldOrientation.xlColumnField;
//fld.Function = Microsoft.Office.Interop.Excel.XlConsolidationFunction.xlSum;
//fld.NumberFormat = "@";

//Data
Excel.PivotField fld = ((Excel.PivotField)pvt.PivotFields("Context Matches"));
fld.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
fld.Function = Microsoft.Office.Interop.Excel.XlConsolidationFunction.xlSum;
fld.NumberFormat = "#,##0_);[Red](#,##0)";

//Data
fld = ((Excel.PivotField)pvt.PivotFields("Words (100)"));
fld.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
fld.Function = Microsoft.Office.Interop.Excel.XlConsolidationFunction.xlSum;
fld.NumberFormat = "#,##0_);[Red](#,##0)";

//define how the xlDataField values are aligned
pvt.DataPivotField.Orientation = Excel.XlPivotFieldOrientation.xlRowField;

Enabling the multiple items filter on the Pivot Table:

C#
//initialize the filter ensuring that all items are checked/selected
fld_projectName.CurrentPage = "(All)";

//Apply the 'Multiple Items' filter on the pivot table.
//This should resemble the same functionality as manullay 
//checking the checkbox for 'Select Multiple Items'
//and then selecting multiple items for the filter.

Excel.PivotFields _PivotFields = 
   (Excel.PivotFields)pvt.get_PageFields(Missing.Value);

foreach (Excel.PivotField _PivotField in _PivotFields)
{
  if (string.Compare(_PivotField.Caption, fld_projectName.Caption, true) == 0)
  {
     Excel.PivotItems _PivotItems = 
        (Excel.PivotItems)_PivotField.PivotItems(Missing.Value);
     foreach (Excel.PivotItem _PivotItem in _PivotItems)
     {
        //Note: only the filter items whose items match ("Proj_1, Proj_2") 
        //will be checked/selected
        if (ListToFilter.Contains(_PivotItem.Caption))
            _PivotItem.Visible = true;
        else
            _PivotItem.Visible = false;
     }
  }
}

//define how the xlDataField values are aligned
pvt.DataPivotField.Orientation = Excel.XlPivotFieldOrientation.xlRowField;

Adding a chart object:

C#
//Add the new chart object

Excel.ChartObjects _ChartObjects = (Excel.ChartObjects)
   (_m_objSheet_Report_1.ChartObjects(Missing.Value));
Excel.ChartObject _ChartObject = _ChartObjects.Add(170, 0, 400, 300);
Excel.Chart _Chart = _ChartObject.Chart;

_Chart.SetSourceData(_m_objRange_Chart, Excel.XlRowCol.xlColumns);
_Chart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DPieExploded;
_Chart.HasTitle = true;
_Chart.ChartTitle.Text = "Italian Word Count % - Example";
_Chart.ChartTitle.Font.Size = 12;
_Chart.ApplyDataLabels(

Microsoft.Office.Interop.Excel.XlDataLabelsType.xlDataLabelsShowNone
, Missing.Value, Missing.Value, Missing.Value, Missing.Value, false
, Missing.Value, true, Missing.Value, Missing.Value);

_Chart.Rotation = 0; //X
_Chart.Elevation = 60; //Y
_Chart.Perspective = 10; //Perspective
_Chart.DepthPercent = 100; //Depth
_ChartObject.Chart.HasLegend = true;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralJust perfect Pin
Member 1353507421-Nov-17 23:40
Member 1353507421-Nov-17 23:40 
QuestionWhat is fld_projectName? Pin
B. Clay Shannon27-Jul-16 6:42
professionalB. Clay Shannon27-Jul-16 6:42 
GeneralRe: What is fld_projectName? Pin
Patrick.Hartnett26-May-17 5:35
Patrick.Hartnett26-May-17 5:35 
QuestionThank you! Pin
jmstanle22-Sep-15 8:11
jmstanle22-Sep-15 8:11 
AnswerRe: Thank you! Pin
Patrick.Hartnett26-May-17 5:36
Patrick.Hartnett26-May-17 5:36 
QuestionRaise event when user check any chek box in filter and click OK button in the Filter Pin
surya from hyderabad26-Mar-15 22:14
surya from hyderabad26-Mar-15 22:14 
AnswerRe: Raise event when user check any chek box in filter and click OK button in the Filter Pin
Patrick.Hartnett26-May-17 5:55
Patrick.Hartnett26-May-17 5:55 
GeneralMy vote of 5 Pin
umta13-Jun-13 6:48
professionalumta13-Jun-13 6:48 
GeneralMy vote of 5 Pin
Octavian130526-Jul-10 22:06
Octavian130526-Jul-10 22:06 
GeneralRe: My vote of 5 Pin
Patrick.Hartnett27-Jul-10 5:42
Patrick.Hartnett27-Jul-10 5:42 
GeneralMy vote of 5 Pin
Bruno Antonini18-Jul-10 23:51
Bruno Antonini18-Jul-10 23:51 
GeneralRe: My vote of 5 Pin
Patrick.Hartnett19-Jul-10 19:49
Patrick.Hartnett19-Jul-10 19:49 
GeneralSource code link is broken Pin
Tony Bermudez18-Jul-10 7:49
Tony Bermudez18-Jul-10 7:49 
GeneralRe: Source code link is broken Pin
Patrick.Hartnett18-Jul-10 20:40
Patrick.Hartnett18-Jul-10 20:40 
GeneralMy vote of 1 Pin
Kunal Chowdhury «IN»17-Jul-10 18:36
professionalKunal Chowdhury «IN»17-Jul-10 18:36 
GeneralRe: My vote of 1 Pin
Patrick.Hartnett17-Jul-10 19:28
Patrick.Hartnett17-Jul-10 19:28 
GeneralRe: My vote of 1 Pin
Kunal Chowdhury «IN»17-Jul-10 19:33
professionalKunal Chowdhury «IN»17-Jul-10 19:33 
Awesome. Changing my vote to 4.


Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralRe: My vote of 1 Pin
laduran11-Nov-13 14:19
laduran11-Nov-13 14:19 
GeneralNot an article. Pin
Dave Kreskowiak17-Jul-10 18:23
mveDave Kreskowiak17-Jul-10 18:23 
GeneralRe: Not an article. Pin
Patrick.Hartnett17-Jul-10 19:28
Patrick.Hartnett17-Jul-10 19:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.