How to Create Pivot Table in Excel using C#

This brief tutorial guides on how to create pivot table in Excel using C#. To create pivot table programmatically C# code and detailed description are provided such that at the end you will get an XLSX (or XLS) file having a pivot table in it without using any other third-party tool. It also contains steps that guide adding different fields to different areas in the pivot table.

Steps to Create pivot Table in C#

  1. Establish the environment to add Aspose.Cells for .NET from the NuGet package manager for creating pivot table
  2. Create or load an existing workbook having data for the pivot table
  3. Get access to the target worksheet where the pivot table is to be added
  4. Create a pivot table and get its instance for further processing
  5. Configure the new pivot table and add different fields to the column, row, and data area
  6. Save the resultant workbook having a pivot table in it

After establishing the environment for C# Excel pivot table generation is described here such that we create a new workbook here having the hardcoded data however you can load an existing Excel file also having target data in it. In the next steps, it further describes the process of creation of a pivotTable and then its configuration. In the final steps, different fields are added to different areas in the pivot table like the column, row, and data.

Code to Create pivot Table in Excel using C#

This sample code demonstrates how to create a pivot table in C# by providing the data range, and destination cell where the pivot table is to be placed along with the pivot table name. The pivotTable class has a function AddFieldToArea() that is used to drag different fields to different areas using pivotFieldType like Column, Row, or Data along with the field number in the selected data range. You can also use another pivotFieldType Page if required.

In this article, we have learned to add Excel pivot table in C#. If you want to learn to export data in a list to Excel, refer to the article on how to export list data to Excel in C#.

 English