简体   繁体   English

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

[英]Can't sort excel worksheet using C#

I want to programmatically sort an excel worksheet using C# but the code I used doesn't work: 我想使用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();

I debug it using the messagebox to print of the value in the column "J" and the result is not sorted: 我使用消息框调试它以打印“ 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);

What's the reason of it not working? 它不起作用的原因是什么?

Thanks 谢谢

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

In your code you open excel then read from it so sheets are read in original order (not sorted alphabetical). 在您的代码中,打开excel,然后从中读取,以便按原始顺序(未按字母顺序)读取工作表。 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)
        {
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM