使用c#对excel中的列进行排序

l--*_*''' 4 c# excel interop

我正在尝试使用INTEROP在Excel中的第一列对工作表进行排序.我只想要第一列的整个范围的简单排序.我正在做以下事情:

 valueRange.Sort(valueRange.Columns[7, Type.Missing], Excel.XlSortOrder.xlAscending, valueRange.Columns[7, Type.Missing],
                Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, 
                Excel.XlYesNoGuess.xlNo, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, 
                Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, 
                Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
Run Code Online (Sandbox Code Playgroud)

但是得到错误.我无法找到有关如何进行此排序的适当文档.

有人可以通过特定列给我一个简单的指定范围的工作示例吗?

根据我试图这样做的文件:

valueRange.Sort(valueRange.Columns[7, Type.Missing],
                        Excel.XlSortOrder.xlAscending,
                        Type.Missing,
                        Type.Missing,
                        Excel.XlSortOrder.xlAscending,
                        Type.Missing,
                        Excel.XlSortOrder.xlAscending,
                        Excel.XlYesNoGuess.xlNo,
                        Type.Missing,
                        Type.Missing,
                        Excel.XlSortOrientation.xlSortColumns,
                        Excel.XlSortMethod.xlStroke,
                        Excel.XlSortDataOption.xlSortNormal,
                        Excel.XlSortDataOption.xlSortNormal,
                        Excel.XlSortDataOption.xlSortNormal);
Run Code Online (Sandbox Code Playgroud)

但是现在我得到了错误:

{"The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank."}
Run Code Online (Sandbox Code Playgroud)

小智 14

为了按该范围内的单个列对范围进行排序,您可以执行以下操作(如果您使用VS 2010及更高版本的"dynamic"关键字):

dynamic allDataRange = worksheet.UsedRange;
allDataRange.Sort(allDataRange.Columns[7], Excel.XlSortOrder.xlDescending);
Run Code Online (Sandbox Code Playgroud)

在我的示例中,我有一个包含10个左右列的电子表格,我想按第7列按降序对整个电子表格进行排序.

我得到了上述答案的帮助,但当我尝试Code4Life的片段时:

dynamic valueRange = GetTheRange();
valueRange.Columns.get_Item(1)).Sort(valueRange.Columns[1]);
Run Code Online (Sandbox Code Playgroud)

它只对范围的第一列进行了排序.OP要求将整个范围排序一列,而不是对一个范围内的一列进行排序.所以经过一些试验和错误后,我得到了上面的简化代码.

  • 谢谢你在使用它们讨厌的COM调用时非常有用. (2认同)