Excel Sort-Sort Excel Data in C#, VB.NET

Sorting Excel data is very useful in Excel. It helps people automatically sort the Excel data information quickly which saves much time and avoid mistakes. This section will introduce a solution to sort Excel data by four ways: Ascending, Descending, Top and Bottom via a .NET Excel component in C#, VB.NET.

Spire.XLS for .NET is a professional Excel component which is applied in .NET applications. This .NET component enables you to sort Excel data both in horizontal and vertical directions. Only by two lines’ of key code, you can easily sort excel data according to your need. First you are required to decide which column that you need to sort by calling this method: Workbook.DataSorter.SortColumn Add(int key, OrderBy orderBy). Then, you can set the cell range that you need to sort through Workbook. DataSorter.Sort(CellRange range). Please view the effect of this task as below picture:

Sort Excel Data

Here you can download Spire.XLS for .NET and install it in your system. After adding Spire.Xls dll from your Bin folder, please follow below code to accomplish your task directly.

[C#]
using Spire.Xls;
using System;
namespace SortData
{
    class Program
    {
        private void button1_Click(object sender, EventArgs e)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"..\sort excel.xlsx");
            Worksheet worksheet = workbook.Worksheets[0];

            //append the sort column index and order by attributes 
            workbook.DataSorter.SortColumns.Add(2, OrderBy.Ascending);

            //set the range to sort.
            workbook.DataSorter.Sort(worksheet["A1:E12"]);

            //save and launch the file5
            workbook.SaveToFile(@"test.xlsx", ExcelVersion.Version2010);
            ExcelDocViewer(@"test.xlsx");
        }
        private void ExcelDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }


        }
    }
VB.NET:
Imports Spire.Xls
Namespace SortData
	Class Program
		Private Sub button1_Click(sender As Object, e As EventArgs)
			Dim workbook As New Workbook()
			workbook.LoadFromFile("..\sort excel.xlsx")
			Dim worksheet As Worksheet = workbook.Worksheets(0)

			'append the sort column index and order by attributes 
			workbook.DataSorter.SortColumns.Add(2, OrderBy.Ascending)

			'set the range to sort.
			workbook.DataSorter.Sort(worksheet("A1:E12"))

			'save and launch the file5
			workbook.SaveToFile("test.xlsx", ExcelVersion.Version2010)
			ExcelDocViewer("test.xlsx")
		End Sub
		Private Sub ExcelDocViewer(fileName As String)
			Try
				System.Diagnostics.Process.Start(fileName)
			Catch
			End Try
		End Sub


	End Class
End Namespace