I'm using ClosedXML with C# to modify an Excel workbook. I need to find the last row number used but .RowCount()
counts how many rows are in the worksheet. So it is returning 1 million rows when there are only a few thousand. I have tried LastRowUsed()
but that doesn't return an int and there is no .row
method for it. How can I get the last row in an int?
Asked
Active
Viewed 2.9k times
16

RBT
- 24,161
- 21
- 159
- 240

Daniel Blois
- 187
- 1
- 1
- 7
-
1Daniel, I think you marked the wrong comment as the answer. – Francois Botha Jan 02 '18 at 13:33
5 Answers
33
The LastRowUsed()
function returns a row object. Use
worksheet.LastRowUsed().RowNumber()
to get the number of the last row used.

Raidri
- 17,258
- 9
- 62
- 65
10
You could use RowsUsed();
var wb = new XLWorkbook();
var ws = wb.worksheets.add("data");
var totalRows = ws.RowsUsed().Count();

bird
- 152
- 10
-
-
1
-
1This doesn't work as expected when there are hidden rows. [@Raidri](https://stackoverflow.com/users/2610249/raidri) answer is the perfect answer for this question. – Bryan Adams Jan 10 '18 at 02:13
5
You have to use .LastRowUsed()
More useful stuff from official GitHub repo
:
range.FirstCell()
range.FirstCellUsed()
range.FirstColumn()
range.FirstColumnUsed()
range.FirstRow()
range.FirstRowUsed()
range.LastCell()
range.LastCellUsed()
range.LastColumn()
range.LastColumnUsed()
range.LastRow()
range.LastRowUsed()

ManishChristian
- 3,759
- 3
- 22
- 50
-
2Just be careful not to use the functions "range.Last..." in a big loop, since they can be slow. Assign the value you need in a variable and use that variable in your loop. As in `IXLCell MyLastCellUsed = ws.LastCellUsed;` – Matt Roy Feb 25 '19 at 16:45
1
I had this problem.
This example has the best performance:
XLWorkbook workbook = new XLWorkbook(FilePath);
// row count
var rowCount = workbook.Worksheet(1).LastRowUsed().RowNumber();
// column count
var columnCount = workbook.Worksheet(1).LastColumnUsed().ColumnNumber();
or
XLWorkbook workbook = new XLWorkbook(FilePath);
// row count
var rowCount = workbook.Worksheet(1).RowsUsed().Count();
// column count
var columnCount = workbook.Worksheet(1).ColumnUsed().Count();
I hope this helps you

Saeid
- 422
- 4
- 9
0
I used this code
libro = new XLWorkbook("file.xlsx");
hoja = libro.Worksheet(1);
var primeraCeldaUsada = hoja.FirstCellUsed();
var ultimaCeldaUsada = hoja.LastCellUsed();
var rango = hoja.Range(primeraCeldaUsada.Address, ultimaCeldaUsada.Address);
int ultfila = int.Parse(ultimaCeldaUsada.Address.RowNumber.ToString());
for (int i = 7; i <= ultfila; i++)
{
hoja.Cell(i, 3).Value = hoja.Cell(i, 3).Address.ToString();
}
-
2Please avoid posting code only answers. Please add some explenation to your code, what it does and why you use this code. – Korashen Nov 15 '18 at 14:49
-
Recorre la columna "i", desde la fila 7 hasta la ultima celda usada y en cada una agrega la posición en curso. – José Gavilán Huaquifil Nov 15 '18 at 17:00