To sort across multiple columns in Excel using C#

和自甴很熟 提交于 2019-12-11 13:14:17

问题


I need to sort across multiple columns in Excel using C#. I am using Microsoft.Office.Interop.Excel for doing this. But the Range.Sort allows me to sort across only three columns. I want to sort across more than three columns? Is there a way that I can use the Excel.Range.Sort method to sort across more than three columns?


回答1:


Before Excel 2007 you were limited to 3 sort keys - Range.Sort won't let you use more. If that's your target version then you'll need to get creative: a couple of possible ideas being to pull the data into your C# code and sort it there, or build an extra worksheet column containing the concatenated keys, then apply Sort as normal.

If you're using Excel 2007 or later exclusively, then there's a much more flexible sorting capability available: Worksheet.Sort. I built a 30x10 table of random numbers in A1:J30 and recorded a macro that sorted on the first five columns. This is what I got (after cleaning and de-duplicating the code somewhat):

With ActiveWorkbook.Worksheets("Sheet1").Sort
    With .SortFields
        .Clear
        .Add Key:=Range("A1:A30"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Add Key:=Range("B1:B30"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Add Key:=Range("C1:C30"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Add Key:=Range("D1:D30"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Add Key:=Range("E1:E30"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    End With
    .SetRange Range("A1:J30")
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

That should be fairly easy to apply to your C# code...



来源:https://stackoverflow.com/questions/10221893/to-sort-across-multiple-columns-in-excel-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!