How to retrieve the last row in .NET Excel Library
16 Aug 20262 minutes to read
The following code examples demonstrate retrieving the last row in the used range of an Excel worksheet using C# (Cross-platform and Windows-specific) and VB.NET.
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Open(Path.GetFullPath(@"Data/Input.xlsx"));
IWorksheet worksheet = workbook.Worksheets[0];
//Get the last row from the used range
int lastrow = workbook.ActiveSheet.UsedRange.LastRow;
//Display the last row
Console.WriteLine("The last row in the used range is: " + lastrow);
//Save the workbook
workbook.SaveAs(Path.GetFullPath(@"Output/Output.xlsx"));
}using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Open("Input.xlsx");
IWorksheet worksheet = workbook.Worksheets[0];
//Get the last row from the used range
int lastrow = workbook.ActiveSheet.UsedRange.LastRow;
//Display the last row
Console.WriteLine("The last row in the used range is: " + lastrow);
//Save the workbook
workbook.SaveAs("Output.xlsx");
}Using excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Xlsx
Dim workbook As IWorkbook = application.Workbooks.Open("Input.xlsx")
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Get the last row from the used range
Dim lastrow As Integer = workbook.ActiveSheet.UsedRange.LastRow
'Display the last row
Console.WriteLine("The last row in the used range is: " & lastrow)
'Save the workbook
workbook.SaveAs("Output.xlsx")
End UsingA complete working example in C# is present on this GitHub page.