基于第一列

时间:2017-05-21 07:36:29

标签: c# excel excel-vba vba

我有一个excel文件如下(有2列 - UserID和一个变量):

variable                UserID
---------------------------------------
0.999999999999901       A3PPXVR5J6U2JD  
7.16184317895728e-10    A3RTKL9KB8KLID  
1.49736349513394e-16    AJVVATHEYX7L9   
5.57811370169348e-25    AOL7V6D4AL3KO   
1.49736349513394e-16    A214RU9GS37U2T  
0                       A2KJFH1F69U5R
4.45695014171021e-07    A38LAIK2N83NH0  
1.49736349513394e-16    A2P9YDRHZTJMC3  
1.49736349513394e-16    A1G2W2C669C8GC
.........
.
.
.

我希望在C#中读取此文件并根据列(1)进行排序。我写了这段代码:

Excel.Workbook xlWorkbook = myExcelApp.Workbooks.Open(Filename: 
@"D:\test.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
xlrange.Sort(xlrange.Columns[1], Excel.XlSortOrder.xlAscending);

我想取这个结果:(按升序排列基于列(1)的文件)

0                       A2KJFH1F69U5R
5.57811370169348e-25    AOL7V6D4AL3KO
....
.
.

但是这会将列作为字符串并基于字符串进行排序。这意味着Code将列(1)作为字符串并对其进行排序。这个答案是代码的结果:

0                       A2KJFH1F69U5R
0.999999999999901       A3PPXVR5J6U2JD  
1.49736349513394e-16    AJVVATHEYX7L9   
.
.
.

我想要正确的代码,这段代码将第一列作为double和sort文件。

1 个答案:

答案 0 :(得分:0)

我认为这应该适合你:

using Excel = Microsoft.Office.Interop.Excel;
class Program
{
    static void Main(string[] args)
    {
        var excelApp = new Excel.Application();
        excelApp.Workbooks.Add();
        // VBA code goes here:
        excelApp.Columns["A:B"].Select
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortFields.Clear
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortFields.Add Key:=Range["A:B"], _
                SortOn:=Excel.XlSortOn.xlSortOnValues, Order:=Excel.XlSortOrder.xlAscending, _
                DataOption:=Excel.XlSortDataOption.xlSortNormal

            excelApp.ActiveWorkbook.Worksheets("test").Sort.SetRange Range["A:B"]
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Header = Excel.XlYesNoGuess.xlGuess
            excelApp.ActiveWorkbook.Worksheets("test").Sort.MatchCase = False
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Orientation = Excel.Constants.xlTopToBottom
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortMethod = Excel.XlSortMethod.xlPinYin
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Apply

        excelApp.Visible = true;
    }
}

您可以找到更多信息here