Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the range of occupied cells in excel sheet

I use C# to automate an excel file. I was able to get the workbook and the sheets it contains. If for example I have in sheet1 two cols and 5 rows. I wanted o get the range for the occupied cells as A1:B5. I tried the following code but it did not give the correct result. the columns # and row # were much bigger and the cells were empty as well.

     Excel.Range xlRange = excelWorksheet.UsedRange;      int col = xlRange.Columns.Count;      int row = xlRange.Rows.Count; 

Is there another way I can use to get that range?

like image 964
Sarah Avatar asked Aug 16 '09 14:08

Sarah


People also ask

How do you select all occupied cells Excel?

Press CTRL+A. Note If the worksheet contains data, and the active cell is above or to the right of the data, pressing CTRL+A selects the current region.


1 Answers

I had a very similar issue as you had. What actually worked is this:

iTotalColumns = xlWorkSheet.UsedRange.Columns.Count; iTotalRows = xlWorkSheet.UsedRange.Rows.Count;  //These two lines do the magic. xlWorkSheet.Columns.ClearFormats(); xlWorkSheet.Rows.ClearFormats();  iTotalColumns = xlWorkSheet.UsedRange.Columns.Count; iTotalRows = xlWorkSheet.UsedRange.Rows.Count; 

IMHO what happens is that when you delete data from Excel, it keeps on thinking that there is data in those cells, though they are blank. When I cleared the formats, it removes the blank cells and hence returns actual counts.

like image 125
Farhan Avatar answered Sep 23 '22 00:09

Farhan