简体   繁体   中英

Insert a row in Excel using EPPlus

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.

Use following code

worksheet.Dimension.End.Row

This should give last used row info.

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.

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