I am trying to get the last row of an excel sheet programatically using the Microsoft.interop.Excel Library and C#. I want to do that, because I am charged with looping through all the records of an excel spreadsheet and performing some kind of operation on them. Specifically, I need the actual number of the last row, as I will throw this number into a function. Anybody have any idea how to do that?
Locate the last cell that contains data or formatting on a worksheet. To locate the last cell that contains data or formatting, click anywhere in the worksheet, and then press CTRL+END.
Ctrl-Down -- The shortcut moves the cursor to the last row with data before the first blank row that is encountered; this may be the last row in the table ideally, but only if there are not any blank rows in the table.
Select this entire row by pressing the shortcut key Shift Space. Step 2: Now hold the Keys Shift & Ctrl > Press down Arrow; it will take you till the end of the last row.
Couple ways,
using Excel = Microsoft.Office.Interop.Excel; Excel.ApplicationClass excel = new Excel.ApplicationClass(); Excel.Application app = excel.Application; Excel.Range all = app.get_Range("A1:H10", Type.Missing);
OR
Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); Excel.Range range = sheet.get_Range("A1", last); int lastUsedRow = last.Row; int lastUsedColumn = last.Column;
This is a common issue in Excel.
Here is some C# code:
// Find the last real row nInLastRow = oSheet.Cells.Find("*",System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious, false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row; // Find the last real column nInLastCol = oSheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value,System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlPrevious, false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Column;
found here
or using SpecialCells
Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); Excel.Range range = sheet.get_Range("A1", last);
[EDIT] Similar threads:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With