I want to programmatically sort an excel worksheet using C# but the code I used doesn't work:
//the largest size of sheet in Excel 2010
int maxRowAmount = 1048576;
int maxColAmount = 16384;
//Sort by the value in column G1
sourceWorkSheet.Sort.SortFields.Add(sourceWorkSheet.Range["J:J"], XlSortOn.xlSortOnValues, XlSortOrder.xlAscending, XlSortDataOption.xlSortNormal);
//Find out the last used row and column, then set the range to sort,
//the range is from cell[2,1](top left) to the bottom right corner
int lastUsedRow=sourceWorkSheet.Cells[maxRowAmount, 1].End[XlDirection.xlUp].Row;
int lastUsedColumn=sourceWorkSheet.Cells[2, maxColAmount].End[XlDirection.xlToLeft].Column;
Range r = sourceWorkSheet.Range[sourceWorkSheet.Cells[2, 1], sourceWorkSheet.Cells[lastUsedRow,lastUsedColumn ]];
sourceWorkSheet.Sort.SetRange(r);
//Sort!
sourceWorkSheet.Sort.Apply();
I debug it using the messagebox to print of the value in the column "J" and the result is not sorted:
//print out the sorted result
Range firstColumn = sourceWorkSheet.UsedRange.Columns[10];
System.Array myvalues = (System.Array)firstColumn.Cells.Value;
string[] cmItem = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();
String msg="";
for (int i = 0; i < 30; i++)
{
msg = msg + cmItem[i] + "\n";
}
MessageBox.Show(msg);
What's the reason of it not working?
Thanks
The solution is to put a
before