I have 7 rows. How to delete rows 2,4,6 at once and shift all other rows so there are no empty rows?
Hi,
You can't delete them at once, but you can delete them in 3 steps:
xls.DeleteRange(new TXlsCellRange(2, 1, 2, 1), TFlxInsertMode.ShiftRowDown);
xls.DeleteRange(new TXlsCellRange(4, 1, 4, 1), TFlxInsertMode.ShiftRowDown);
xls.DeleteRange(new TXlsCellRange(6, 1, 6, 1), TFlxInsertMode.ShiftRowDown);
If they are continuous, you can delete them all at once. Say to delete rows 2 to 6:
xls.DeleteRange(new TXlsCellRange(2, 1, 6, 1), TFlxInsertMode.ShiftRowDown);
But you need to call DeleteRange sequentially if the ranges are not continuous. If you want, you could define a method like this:
static void DeleteRows(ExcelFile xls, params int[] rows)
{
foreach (var row in rows)
{
xls.DeleteRange(new TXlsCellRange(row, 1, row, 1), TFlxInsertMode.ShiftRowDown);
}
}
Sorry, I am a little asleep today... of course the code should be:
xls.DeleteRange(new TXlsCellRange(6, 1, 6, 1), TFlxInsertMode.ShiftRowDown);
xls.DeleteRange(new TXlsCellRange(4, 1, 4, 1), TFlxInsertMode.ShiftRowDown);
xls.DeleteRange(new TXlsCellRange(2, 1, 2, 1), TFlxInsertMode.ShiftRowDown);
and
static void DeleteRows(ExcelFile xls, params int[] rows)
{
Array.Sort(rows);
for (int i = rows.Length - 1; i >= 0; i--)
{
if (i == rows.Length - 1 || rows[i] != rows[i + 1])
{
xls.DeleteRange(new TXlsCellRange(rows[i], 1, rows[i], 1), TFlxInsertMode.ShiftRowDown);
}
}
}
With the original code I posted, if you delete row2, then row4 will move to be row3, and when you delete row4 you will be deleting row5.
For the DeleteRows
method, we also take in account that if you delete 2 times row 4, it should delete it just once. So if you call
DeleteRows(xls, 3, 4, 1, 4);
If will only delete row 4 once, not 2 times. (the second time it would be deleting row 5)