When I try and call Cells[fullRow, 1].get_end I get an error, object does not contain a definition for get_end and no extension method could be found.
I never saw anyone complain about this or describe this in comments of old stack overflow threads re the subject of finding last row in an excel column using C#
string path = @"Z:\New folder\Test123.xlsx";
MyApp = new Excel.Application();
MyApp.Visible = true;
MyBook = MyApp.Workbooks.Open(path);
MySheet = (Excel.Worksheet)MyBook.Sheets[1];
int fullRow = MySheet.Rows.Count;
int LastRow = MySheet.Cells[1,1].get_end(Excel.XlDirection.xlUp).Row;
If you assign the return from MySheet.Cells[1, 1]
in to a Range object or call the function End
, you should find that it works as expected. Also, note the case of the function, it is meant to be: get_End
.
// Working
Excel.Range firstCell1 = MySheet.Cells[1, 1];
int LastRow1 = firstCell1.get_End(Excel.XlDirection.xlUp).Row;
// Working
Excel.Range firstCell2 = MySheet.Cells[fullRow, 1];
int LastRow2 = firstCell2.get_End(Excel.XlDirection.xlUp).Row;
// Working
int LastRow3 = MySheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row;
// Does not work
int LastRow4 = MySheet.Cells[1, 1].get_End(Excel.XlDirection.xlUp).Row;
I believe the problem is down to the Dynamic Binding done at runtime for COM Interop, but, I am not 100% certain of the reason.
You can use something like this
void Main()
{
Microsoft.Office.Interop.Excel.Application app;
Microsoft.Office.Interop.Excel.Workbook wkb;
app = new Microsoft.Office.Interop.Excel.Application();
wkb = app.Workbooks.Open(@"e:\temp\test.xlsx");
int row = GetLastRow(wkb, "sheet1", "A");
Console.WriteLine(row);
app.Quit();
}
int GetLastRow(Workbook wkb, string sheet, string column)
{
Microsoft.Office.Interop.Excel.Worksheet sht = wkb.Worksheets[sheet] as Worksheet;
Microsoft.Office.Interop.Excel.Range range = sht.Range[column + ":" + column];
range = range.Cells[range.Rows.Count, range.Column] as Range;
return range.End[XlDirection.xlUp].Row;
}
You can remove all that Microsoft.Office.Interop.Excel stuff adding the appropriate using directive.
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.