Open Excel File, sort Range, and Save changes [C#]

Shaitan00

Well-known member
Joined
Aug 11, 2003
Messages
343
Location
Hell
Okay - I thought my code would work but for some odd reason it doesnt seem to make any differences, either it isnt working or not saving the changes at the end (I am not 100% sure) - so I was hoping someone could take a look and tell me if I did something wrong...
My Excel File is called [Tasks.xls] and has a worksheet [Tasks] that has 4 columns as illustrated below:

[Tasks.Xls]
[CLIENTS] [ASSINGMENTS] [STATUS] [StartTime]
Client1 Assignment1 ACTIVE 09/01/2005
Client2 Assignment2 ACTIVE 09/02/2005
Client1 Assignment2 ACTIVE 09/05/2005
Client2 Assignment1 ACTIVE 09/12/2005
... etc ...

My goal is to SORT this Excel file so it looks like this:
Client1 Assignment1 ACTIVE 09/01/2005
Client1 Assignment2 ACTIVE 09/05/2005
Client2 Assignment1 ACTIVE 09/12/2005
Client2 Assignment2 ACTIVE 09/02/2005
... etc ...

Therefore Sort by column [CLIENTS] in acending - so find below the code I am using.

Code:
Excel.Application sXL = new Excel.Application();
Excel._Workbook oWB = sXL.Workbooks.Open(System.Windows.Forms.Application.StartupPath + "\\Tasks.xls",Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
Excel._Worksheet oSheet = (Excel._Worksheet)oWB.Sheets["Tasks"];
Excel.Range oRng = oSheet.get_Range("A1", "D1");
oRng.Sort(oRng.Columns[1, Type.Missing], Excel.XlSortOrder.xlAscending, oRng.Columns[2,Type.Missing], Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlNo, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
oWB.Save();
sXL.Quit();

What am I doing wrong? The code runs fine (no errors) but when I open my Excel [.xLS] file nothing has changed - meaning it is not sorted as expected.
Can it be the way I OPEN the File/Workbook/Worksheet, sort it, save it? etc...
Any help/hints would be appreciated, thanks.
 
From the code youve posted, it looks like the range youre trying to sort only has 1 row (A1:D1). Sorting a single row wouldnt really be visible. Redefining oRng so that it covers the entire range might solve the problem.

In any case, if youre not sure whether the sorting is failing, or whether the saving is going wrong, just make the Excel application visible and step through the code line by line, and look at what Excel does.
 
Back
Top