简体   繁体   中英

How to sort data by column excluding the first row

I need to sort a worksheet by the 11th column. This code works but includes the column header so that it moves down the worksheet.

I have already tried the below code

worksheet.Cells[1, 1].EntireRow.Font.Bold = true;
var startCell = (Excel.Range)worksheet.Cells[1, 1];
var endCell = (Excel.Range)worksheet.Cells[row, 12];

Excel.Range range = worksheet.Range[startCell, endCell];
range.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders.Weight = Excel.XlBorderWeight.xlThin;

Excel.Range fullDataRange = worksheet.UsedRange;
fullDataRange.Sort(fullDataRange.Columns[11], 
Excel.XlSortOrder.xlAscending);

excelApp.ActiveWorkbook.SaveAs(txtOutputFolder.Text + "\\" + 
filestart + " Instructions" + DateTime.Now.ToString(" dd.MM") + ".xlsx");
            excelApp.ActiveWorkbook.Close();

您可以选择所需的范围:

 worksheet.Range("A1:H8")

If you check the Sort documentation you will see that you can specify if the sort range has a header. Just add a named parameter to you sort command :

fullDataRange.Sort(fullDataRange.Columns[11], Excel.XlSortOrder.xlAscending, Header:xlYes);

and the first row will be ignored when sorting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM