How do I delete all rows in an excel spreadsheet except the header in c#?
I am trying to do this using the Microsoft.Office.Interop.Excel;
library
I now have this code
Range xlRange = ws.UsedRange;
int rows = xlRange.Rows.Count;
Console.WriteLine(rows);
for (int i = 2; i <= rows; i++)
{
((Range)ws.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
}
But it's not deleting all the rows, I think because it's deleting the rows when it hits a certain number that row is no longer there, what have I done wrong?
I managed to do it, I have started from the bottom instead of the top, so now my loop is
for (int i = rows; i != 1; i--)
{
((Range)ws.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
}
Solution
var range = (Range)ws.Range[ws.Cells[2, 1], ws.Cells[ws.UsedRange.Rows.Count, ws.UsedRange.Columns.Count]];
range.Delete(XlDeleteShiftDirection.xlShiftUp);
There had been a change in v4 of .Net that using get_Range
stopped working