无法使用 C# 对 excel 工作表进行排序

Can't sort excel worksheet using C#

我想使用 C# 以编程方式对 excel 工作表进行排序,但我使用的代码不起作用:

        //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();

我使用消息框调试它以打印列 "J" 中的值,但结果未排序:

        //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);

为什么不能用?

谢谢

解决办法是放一个

sourceWorkSheet.Sort.SortFields.Clear(); 

之前

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

在您的代码中,您打开 excel 然后从中读取,以便按原始顺序读取工作表(不按字母顺序排序)。 您可以使用下一个代码来获取排序的工作表。

        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)
        {
        }