Articles in this section
Category / Section

How to sort pivot fields in Excel using XlsIO?

4 mins read

This article explains how to sort pivot fields in Excel using XlsIO.

What is a Pivot Table?

A pivot table is a program tool that allows you to reorganize and summarize selected columns and rows of data in a spreadsheet or database table to obtain a desired report.

A pivot table is used to build a list of unique values because pivot tables summarize data, and can be used to find unique values in a field. This is a good way to quickly see all the values that appear in a field.

Sample code to sort pivot fields in Excel using XlsIO

// Sort pivot field items in the given order
IPivotField pivotField = pivotTable.Fields[0];
pivotField.Sort(new string[3] { pivotField.Items[1].Text, pivotField.Items[2].Text, pivotField.Items[0].Text });

NOTE: This is applicable to apply custom sorting in a pivot table.

Download Complete Sample

The following C#/VB complete code snippet shows how to sort pivot fields in Excel using XlsIO.

C#

using Syncfusion.XlsIO;
using System;
using System.Collections.Generic; 
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace PivotTable
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                // Instantiate the Excel application object
                IApplication application = excelEngine.Excel;
 
                // The workbook is opened
                IWorkbook workbook;
 
                // Open existing workbook with data entered
                Assembly assembly = typeof(Program).GetTypeInfo().Assembly;
                Stream fileStream = assembly.GetManifestResourceStream("PivotTable.Sample.xlsx");
 
                workbook = application.Workbooks.Open(fileStream, ExcelOpenType.Automatic);
                // The first worksheet object in the worksheets collection is accessed
                IWorksheet pivotDataSheet = workbook.Worksheets[0];
                // A new worksheet is added into the workbook
                IWorksheet pivotTableSheet = workbook.Worksheets.Create();
 
                // Adding pivot table
                IPivotCache cache = workbook.PivotCaches.Add(pivotDataSheet["A1:D16"]);
                IPivotTable pivotTable = pivotTableSheet.PivotTables.Add("PivotTable1", pivotTableSheet["A1"], cache);
 
                pivotTable.Fields[0].Axis = PivotAxisTypes.Column;
                pivotTable.Fields[1].Axis = PivotAxisTypes.Row;
 
                // Adding data fields to pivot table
                pivotTable.DataFields.Add(pivotTable.Fields[2], "Sum", PivotSubtotalTypes.Sum);
                pivotTable.DataFields.Add(pivotTable.Fields[3], "Avg", PivotSubtotalTypes.Average);
 
                // Sorting pivot field items in the given order
                IPivotField pivotField = pivotTable.Fields[0];                
                pivotField.Sort(new string[3] { pivotField.Items[1].Text, pivotField.Items[2].Text, pivotField.Items[0].Text });
 
                // Saving and closing the workbook
                Stream stream = File.Create("Output.xlsx");
                pivotDataSheet.UsedRange.AutofitColumns();
                workbook.SaveAs(stream);
            }
        }
    }
}
 

 

VB

Imports Syncfusion.XlsIO
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Reflection
Imports System.Text
Imports System.Threading.Tasks
 
Namespace PivotTable
 
    Class Program
 
        Private Shared Sub Main(ByVal args() As String)
            Dim excelEngine As ExcelEngine = New ExcelEngine
            'Instantiate the Excel application object
            Dim application As IApplication = excelEngine.Excel
            'The workbook is opened
            Dim workbook As IWorkbook
 
            'Open existing workbook with data entered
            Dim assembly As Assembly = GetType(Program).GetTypeInfo.Assembly
            Dim fileStream As Stream = assembly.GetManifestResourceStream("PivotTable.Sample.xlsx")
 
            workbook = application.Workbooks.Open(fileStream, ExcelOpenType.Automatic)
            'The first worksheet object in the worksheets collection is accessed
            Dim pivotDataSheet As IWorksheet = workbook.Worksheets(0)
            'A new worksheet is added into the workbook
            Dim pivotTableSheet As IWorksheet = workbook.Worksheets.Create
 
            'Adding pivot table
            Dim cache As IPivotCache = workbook.PivotCaches.Add(pivotDataSheet("A1:D16"))
            Dim pivotTable As IPivotTable = pivotTableSheet.PivotTables.Add("PivotTable1", pivotTableSheet("A1"), cache)
 
            pivotTable.Fields(0).Axis = PivotAxisTypes.Column
            pivotTable.Fields(1).Axis = PivotAxisTypes.Row
 
            'Adding data fields to pivot table
            pivotTable.DataFields.Add(pivotTable.Fields(2), "Sum", PivotSubtotalTypes.Sum)
            pivotTable.DataFields.Add(pivotTable.Fields(3), "Avg", PivotSubtotalTypes.Average)
            'Sorting pivot field items in the given order
            Dim pivotField As IPivotField = pivotTable.Fields(0)
            pivotField.Sort(New String() {pivotField.Items(1).Text, pivotField.Items(2).Text, pivotField.Items(0).Text})
 
            'Saving and closing the workbook
            Dim stream As Stream = File.Create("Output.xlsx")
            pivotDataSheet.UsedRange.AutofitColumns()
            workbook.SaveAs(stream)
        End Sub
    End Class
End Namespace
 

 

Take a moment to peruse the documentation where you can find basic Excel document processing options along with the features like import and export data, chart, formulas, conditional formatting, data validation, tables, pivot tables and, protect the Excel documents, and most importantly, the PDF, CSV and Image conversions with code examples.

 

Conclusion

I hope you enjoyed learning about How to sort pivot fields in Excel using XlsIO.

You can refer to our XIsIO’s feature tour page to learn about its other groundbreaking features. Explore our UG documentation and online demos to understand how to manipulate data in Excel documents.

If you are an existing user, you can access our latest components from the License and Downloads page. For new users, you can try our 30-day free trial to check out XlsIO and other Syncfusion® components.

If you have any queries or require clarification, please let us know in the comments below or contact us through our support forumsSupport Tickets, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied