如何使用 vb.net 以编程方式对 Excel 中的列进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/560750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:04:11  来源:igfitidea点击:

How to sort columns in Excel programmatically using vb.net?

vb.netexcel

提问by Suman

we are generating an Excel report and we need to sort the data programmatically before saving the file.

我们正在生成一个 Excel 报告,我们需要在保存文件之前以编程方式对数据进行排序。

Is it possible to sort a specific column of an Excel file programmatically using vb.net?

是否可以使用 vb.net 以编程方式对 Excel 文件的特定列进行排序?

As per your suggestion, in order to generate excel report with sorting on specific column I just implemented the logic as below..

根据您的建议,为了生成对特定列进行排序的 excel 报告,我刚刚实现了如下逻辑。

Dim MyRange As Excel.Range
  gobjExcelReportSheet.Activate()
      MyRange = gobjExcelReportSheet.Range("A8", "L8")
      MyRange.Select()
      MyRange.Sort(Key1:=MyRange.Range("L8"), _
                   Order1:=XlSortOrder.xlAscending, _
                   Header:=XlYesNoGuess.xlGuess, _
                   MatchCase:=False, _
                   Orientation:=XlSortOrientation.xlSortColumns)

I tried this logic just before saving the file and even just after saving the file but it is not giving any result i.e. with sorting result or even I am not getting any error.

我在保存文件之前甚至在保存文件之后尝试了这个逻辑,但它没有给出任何结果,即排序结果,甚至我没有收到任何错误。

But the following code works....

但以下代码有效....

gobjExcelReportSheet.Application.Selection.Autofilter()

gobjExcelReportSheet.Application.Selection.Autofilter()

But there is no option for sorting programmetically.

但是没有以编程方式排序的选项。

Please help me...

请帮我...

Thanks!

谢谢!

回答by RobS

Assuming you're using the interop assemblies this is how I do it:

假设您正在使用互操作程序集,这就是我的做法:

Dim myWorkSheet As Excel.Worksheet = myWorkbook.Worksheets(aSheetName)
myWorkSheet.Activate()
Dim myRange As Excel.Range

myRange = myWorkSheet.Range("A1", "L10")
myRange.Select()


myRange.Sort(Key1:=myRange.Range("D1"), _
                        Order1:=Excel.XlSortOrder.xlAscending, _
                        Orientation:=Excel.XlSortOrientation.xlSortColumns)

Basically you need to select a range (in this case A1:L10, then choose to sort it by a certain column (D).

基本上,您需要选择一个范围(在本例中为 A1:L10,然后选择按特定列 (D) 对其进行排序)。