Getting the last Excel row in a given worksheet has lots of nice answers here. However, sometimes all we need is the last row of a given column and not of the whole spreadsheet.
I thought of a solution, which seems a bit slow:
- find the last row in Excel for all columns;
- start looping from there to 1, in the specific column, trying to find the first cell which is not empty. This is the result;
- for empty first row and only first row in a given column, always return 1;
This is the implementation:
namespace ExcelTest
{
using System;
using Excel = Microsoft.Office.Interop.Excel;
public class Startup
{
const string filePath = @"C:\Users\gropc\Desktop\Sample.xlsx";
static void Main()
{
Excel.Application excel = new Excel.Application { Visible = true, EnableAnimations = false };
Excel.Workbook wkb = Open(excel, filePath);
foreach (Excel.Worksheet wks in wkb.Worksheets)
{
int lastRowA = LastRowPerColumn(1, wks);
int lastRowB = LastRowPerColumn(2, wks);
int lastRowC = LastRowPerColumn(3, wks);
Console.WriteLine($"{lastRowA} - {lastRowB} - {lastRowC}");
}
wkb.Close(true);
excel.Quit();
}
static int LastRowPerColumn(int column, Excel.Worksheet wks)
{
int lastRow = LastRowTotal(wks);
while (((wks.Cells[lastRow, column]).Text == "") && (lastRow != 1))
{
lastRow--;
}
return lastRow;
}
static int LastRowTotal(Excel.Worksheet wks)
{
Excel.Range lastCell = wks.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
return lastCell.Row;
}
static Excel.Workbook Open(Excel.Application excelInstance,
string fileName, bool readOnly = false,
bool editable = true, bool updateLinks = true)
{
return excelInstance.Workbooks.Open(fileName, updateLinks, readOnly);
}
}
}
Dependencies:
using Excel = Microsoft.Office.Interop.Excel
;const string filePath = @"C:\Users\gropc\Desktop\Sample.xlsx";
Question:
Any ideas to avoid the looping? In vba the solution is quite charming in 1 line:
lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
Anything similar for the C# Excel Interop?