Using C# to sort a column in Excel

前端 未结 2 408
盖世英雄少女心
盖世英雄少女心 2020-12-19 17:34

I am trying to sort a worksheet by the first column in excel using INTEROP.

I just want a simple sort of the entire range by the first column. I am doin

2条回答
  •  感情败类
    2020-12-19 17:37

    In order to sort a range by a single column in that range, you can do something like the following (if you are using VS 2010 and above with the "dynamic" keyword):

    dynamic allDataRange = worksheet.UsedRange;
    allDataRange.Sort(allDataRange.Columns[7], Excel.XlSortOrder.xlDescending);
    

    In my example, I had a spreadsheet with 10 or so columns, and I wanted to sort the entire spreadsheet by the 7th column, in descending order.

    I was helped by the above answer, but when I tried Code4Life's snippet:

    dynamic valueRange = GetTheRange();
    valueRange.Columns.get_Item(1)).Sort(valueRange.Columns[1]);
    

    it only sorted the first column of the range. The OP asked for sorting an entire range by one column, not sorting one column in a range. So after a little trial and error I got my above simplified code.

提交回复
热议问题