Reputation: 65238
I do not see a way to insert a row in an existing excel file using EPPlus. I am aware of the InsertRow function but this does not insert the row at the end - similar to the insert statement in sql. If this is not possible, how would I find the last used row in an excel file.
Upvotes: 1
Views: 14314
Reputation: 121
Use following code
worksheet.Dimension.End.Row
This should give last used row info.
Upvotes: 3
Reputation: 42344
Here is a method that finds the last cell in a table in an Excel worksheet using EPPlus.
private ExcelRange GetLastContiguousCell(ExcelRange beginCell)
{
var worksheet = beginCell.Worksheet;
var beginCellAddress = new ExcelCellAddress(beginCell.Start.Row, beginCell.Start.Column);
var lastCellAddress = worksheet.Dimension.End;
var bottomCell = worksheet.Cells[beginCellAddress.Row, beginCellAddress.Column, lastCellAddress.Row, beginCellAddress.Column]
.First(cell => cell.Offset(1, 0).Value == null);
var rightCell = worksheet.Cells[beginCellAddress.Row, beginCellAddress.Column, beginCellAddress.Row, lastCellAddress.Column]
.First(cell => cell.Offset(0, 1).Value == null);
return worksheet.Cells[bottomCell.Start.Row, rightCell.Start.Column];
}
An important note, however, is that this assumes there are no gaps in the first row and first column. I use this method for situations where the first row is for column headings (which can't be null) and the first column is a primary Id
column (which also can't be null). If your situation differs from this, you will have to adapt the method, but hopefully it will still help.
Edit
It just occurred to me that you might just be able to use worksheet.Dimension.End
without all the other code. I use this more complicated method because I sometimes put other information besides the table in my worksheet, and I don't want that to be included in the calculation.
Upvotes: 1