Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to sort an Excel worksheet using C# EPPLUS. I have reviewed the sort code method here

I am doing this
C#
` var startRow = 11;    
    var startColumn= 1;
    var endRow= 150;
    var endColumn= 41;
    var sortColumn = 1; 
    using (ExcelRange excelRange =
    yourWorkSheet.Cells[startRow,startColumn, endRow, endColumn])
    {
    excelRange.Sort(sortColumn, true);
    }
     `

but that is not working.

The first two columns define what kind of record it is ex. column one GSMO column 2 is Cost. There are 6 types of record for GSMO ex GSMO Cost GSMO Profit GSMO LOSS etc.. Then it starts with another value in column 1 such as SESS etc all the way down to the final row The columns from 3 to 41 are the dollar values associated with the row. So when I sort ascending on column one I want the rest of the columns (2-41) to stay with the same row. I hope this makes sense. Any help would be appreciated Thanks

What I have tried:

C#
` var startRow = 11;
var startColumn= 1;
var endRow= 150;
var endColumn= 41;
var sortColumn = 1;
using (ExcelRange excelRange =
yourWorkSheet.Cells[startRow,startColumn, endRow, endColumn])
{
excelRange.Sort(sortColumn, true);
}
`

but that is not working.

and variations of this
C#
curWorksheet.Cells[11, 0, 148, 41].Sort(new int[] { 1, 41 }, new bool[] { false, false });

and neither is this one I either get range exceptions or column exceptions. ultimately I am using Excel offsets so the numbers in the cells will be variables based upon the expansion of the offset after the addition of the new rows that I will be adding.
Posted
Updated 24-Dec-22 11:09am
v3

1 solution

you can try this:
dynamic allDataRange = yourWorkSheet.UsedRange;
allDataRange.Sort(allDataRange.Columns[1], Excel.XlSortOrder.xlDescending);



to sort in certain range use the code below before the code above:
Excel.Range last = xlWorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = xlWorkSheet.get_Range("B3", last);

note: change "B3" to the cell you want to begin with.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900