Can't sort excel worksheet using C#

1.6k views Asked by At

I want to programmatically sort an excel worksheet using C# but the code I used doesn't work:

        //the largest size of sheet in Excel 2010
        int maxRowAmount = 1048576;
        int maxColAmount = 16384;

        //Sort by the value in column G1
        sourceWorkSheet.Sort.SortFields.Add(sourceWorkSheet.Range["J:J"], XlSortOn.xlSortOnValues, XlSortOrder.xlAscending, XlSortDataOption.xlSortNormal);

        //Find out the last used row and column, then set the range to sort,
        //the range is from cell[2,1](top left) to the bottom right corner
        int lastUsedRow=sourceWorkSheet.Cells[maxRowAmount, 1].End[XlDirection.xlUp].Row;
        int lastUsedColumn=sourceWorkSheet.Cells[2, maxColAmount].End[XlDirection.xlToLeft].Column;
        Range r = sourceWorkSheet.Range[sourceWorkSheet.Cells[2, 1], sourceWorkSheet.Cells[lastUsedRow,lastUsedColumn ]];
        sourceWorkSheet.Sort.SetRange(r);

        //Sort!
        sourceWorkSheet.Sort.Apply();

I debug it using the messagebox to print of the value in the column "J" and the result is not sorted:

        //print out the sorted result
        Range firstColumn = sourceWorkSheet.UsedRange.Columns[10];
        System.Array myvalues = (System.Array)firstColumn.Cells.Value;
        string[] cmItem = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();
        String msg="";
        for (int i = 0; i < 30; i++)
        {
            msg = msg + cmItem[i] + "\n";
        }
        MessageBox.Show(msg);

What's the reason of it not working?

Thanks

2

There are 2 answers

0
Kent Lee On BEST ANSWER

The solution is to put a

sourceWorkSheet.Sort.SortFields.Clear(); 

before

sourceWorkSheet.Sort.SortFields.Add(sourceWorkSheet.Range["J:J"], XlSortOn.xlSortOnValues, XlSortOrder.xlAscending, XlSortDataOption.xlSortNormal);
0
Aya Aboud On

In your code you open excel then read from it so sheets are read in original order (not sorted alphabetical). You can use next code to get sorted sheets.

        OleDbConnection connection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=\"Excel 8.0;HDR=No;\"", filePath));
        OleDbCommand command = new OleDbCommand();
        DataTable tableOfData = null;
        command.Connection = connection;
        try
        {
            connection.Open();
            tableOfData = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string tablename = tableOfData.Rows[0]["TABLE_NAME"].ToString();
            tableOfData = new DataTable();
            command.CommandText = "Select * FROM [" + tablename + "]";
            tableOfData.Load(command.ExecuteReader());
        }
        catch (Exception ex)
        {
        }