C#/VB.NET: Sort Data in Excel

Sorting in Excel is one of the most commonly used features in data analysis. It allows users to sort text, numbers, dates and times in ascending, descending or alphabetical order. This article will demonstrate how to programmatically sort data in a cell range using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Sort Data in Excel

The detailed steps are as follows.

  • Create a Workbook instance.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get the first worksheet using Workbook.Worksheets[index] property.
  • Get a sort fields collection using Workbook.DataSorter.SortColumns property, and then specify the column that need to be sorted and the sort mode in the collection using SortColumns.Add(Int key, SortComparsionType, OrderBy) method.
  • Sort the data in the specified cell range using Workbook.DataSorter.Sort(CellRange range) method.
  • Save the result document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace SortData
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();

            //Load a sample Excel document
            workbook.LoadFromFile("sample.xlsx");

            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Specify the column that need to be sorted and the sort mode (ascending or descending)
            workbook.DataSorter.SortColumns.Add(0, SortComparsionType.Values, OrderBy.Ascending);

            //Sort data in the specified cell range
            workbook.DataSorter.Sort(worksheet.Range["A1:D10"]);

            //Save the result document
            workbook.SaveToFile("Sort.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Sort Data in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.