Sorting excel sheet in reverse order on basis of created time / reversing the excel sheet
I'm using Microsoft interop excel to automate the excel workboook in which i have many worksheets(say 40) which have been created at in seconds gap or even less now i have to present the worksheet in reverse o开发者_高级运维rder i.e the sheet which was created first should come first while opening(currently it comes last) in short I have to sort the excel sheet in reverse order or by time of creation
any help in this matter
thnx
Workbook wb = app.Workbooks.Open(Form1.strRecentFilename, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp);
int count = wb.Worksheets.Count;
Worksheet ws, lastws;
lastws = (Worksheet)wb.Worksheets[count];
MessageBox.Show(lastws.Name);
for (int i = count - 1; i >= 1; i--)
{
lastws = (Worksheet)wb.Worksheets[count];
ws = (Worksheet)wb.Worksheets[i];
ws.Move(System.Reflection.Missing.Value, lastws);
}
As far as I know, Excel doesn't store the date and time of creation of each sheet. Yet, every new sheet is added at the end of every sheets of the workbook.
So, you can reverse the order based on this hypothesis.
Here is a VBA macro to do this, you just have to adapt it to interop or C#:
Sub reverseOrder()
Dim i As Integer
For i = Worksheets.Count - 1 To 1 Step -1
Worksheets(i).Move After:=Worksheets(Worksheets.Count)
Next i
End Sub
It parses sheets from one sheet before the last one to the first one and move each sheet to the last position.
So, if you have a Worksheets of Workbook in excel file and you need to sort Worksheets alphabet:
public void SortWs()
{
List<Worksheet> for_sort = new List<Worksheet>();
foreach (Worksheet ws in wb.Worksheets)
{
for_sort.Add(ws);
}
for_sort.Sort(delegate(Worksheet wst1, Worksheet wst2)
{
return wst1.Name.CompareTo(wst2.Name);//sort by worksheet's name
});
Worksheet ws1, ws2;
for (int i = 0; i < for_sort.Count; i++)
{
for (int j = 1; j <= wb.Worksheets.Count; j++)
{
ws1 = (Worksheet)wb.Worksheets[j];
if (for_sort[i].Name == ws1.Name)
{
ws2 = (Worksheet)wb.Worksheets[i+1];
ws1.Move(ws2, Type.Missing);
}
}
}
}
精彩评论